I’ll explain you how to find a certain element’s index in a JavaScript array in this blog post. This technique covers edge situations, like the element not being found, and is easy to use.
With an in-depth and optimised code sample, you will gain insights into improving your array search logic regardless of your level of experience as a developer.
Want to remove an element from an array? Read it here!
// Defining an array of numbers const numbers = [12, 34, 23, 64, 23, 56, 24]; // Element to search for within the array let searchElement = 23; function findElement(numbers, searchElement) { // Get the length of the array to avoid recalculating it in the loop const length = numbers.length; // Iterate through the array to find the element for (let i = 0; i < length; i++) { // Check if the current element matches the searchElement if (searchElement === numbers[i]) { // Return the index of the found element return i; } } // Return undefined if the element is not found (optional, implicitly returns undefined otherwise) return undefined; } // Call the function and store the index of the element let index = findElement(numbers, searchElement); // Check if the element was found and log the result if (index !== undefined) { console.log(`${searchElement} is found at index ${index}`); } else { console.log(`${searchElement} is not found in the array.`); }
Happy Coding!
Follow our Social Channels
[…] If you want to find an element from an array without using the array method, read it here. […]