In this article, we will learn how to check if a value exists at a certain array index in JavaScript. Arrays are used to store multiple values in a single variable. Each value in an array has a numeric index, starting from zero. You can access the values in an array using their index. In JavaScript, there are different ways to check if a value exists at a specific index in an array.
- Using the typeof operator
- Using the in operator
- Using the hasOwnProperty() methodÂ
Approach: The following approaches will be used to check whether the value exists at a certain array index.
1. Using the typeof operator: In JavaScript, the typeof operator returns the data type of its operand in the form of a string. The operand can be any object, function, or variable. If the value is undefined, then it doesn’t exist.
Â
Syntax:
typeof (operand)
Example: In this example, we will see the use of typeof operator for checking the value.
Javascript
let arr = [1, 2, 3, 4, 5]; let value = 3;   if ( typeof arr[value] !== "undefined" ) {     console.log(`Value ${value} exists         at index ${value - 1}`); } else {     console.log(`Value ${value} doesn't         exist at index ${value - 1}`); } |
Value 3 exists at index 2
2. Using the in operator: The in operator checks if a given property or index exists in the object. For an array, you can use the in operator to check if an index exists or not.
Syntax:
prop in object
Example: In this example, we will see the use of in operator.
Javascript
let arr = [1, 2, 3, 4, 5]; let n = 3;   if (n in arr) {     console.log(`Value ${n} exists         at index ${arr.indexOf(n)}`); } else {     console.log(`Value ${n} does not         exist in the array`); } |
Value 3 exists at index 2
The code then uses an if-else statement to check the result of the in operator and print an appropriate message to the console.
3. Using the hasOwnProperty() method: The hasOwnProperty() method is used to check if an object has a specific property or index. In the case of an array, you can use this method to check if an index exists.
Syntax:
object.hasOwnProperty( prop )
Example: In this example, we will see the use hasOwnProperty() method.
Javascript
const arr = [ 'Geeksforneveropen' , 'GFG' , 'gfg' ]; Â Â if (arr.hasOwnProperty(1)) { Â Â Â Â console.log(arr[1]); Â Â Â Â console.log( 'The index exists in the array' ) } else { Â Â Â Â console.log( 'The specified index does NOT exist' ); } |
GFG The index exists in the array