9 February 2024

In JavaScript, if you want to get the index of an element in an array based on its value, you can use the indexOf() method. If the value is not found in the array, the indexOf() method will return -1. So, you can check if the index is -1 to determine if the value exists in the array or not.

Source code viewer
  1. // Sample array
  2. var array = [10, 20, 30, 40, 50];
  3.  
  4. // Get the index of a specific value
  5. var value = 30;
  6. var index = array.indexOf(value);
  7.  
  8. // Check if the value exists in the array
  9. if (index !== -1) {
  10. console.log("Index of " + value + " is: " + index);
  11. } else {
  12. console.log(value + " is not found in the array.");
  13. }
  14.  
  15. // This code will output: "Index of 30 is: 2", because 30 is located at index 2 in the array.
Programming Language: Javascript