Determine if an element exist at specific index in an array in JavaScript
This post will discuss how to determine whether an element exists at the specified index in an array in JavaScript.
An array in JavaScript can store elements of any type such as number, string, boolean, bigint, null, undefined, symbol, or an object.
1. Check for undefined value
An undefined value automatically gets assigned in JavaScript, where no value has been explicitly assigned. If you don’t specify all elements in an array literal, an undefined value is substituted for the unspecified elements.
To check for an undefined value at the specified index in the array, you can use the following code:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
var arr = [ 1, 2,,,3, 4 ]; var index = 2; if (typeof arr[index] !== 'undefined') { console.log("Element exist at the specified index."); } else { console.log("The value at the specified index is undefined."); } /* Output: The value at the specified index is undefined. */ |
2. Check for nullish value
A nullish value is either null or undefined. To check if a nullish value exists at the specified index in the array, you can use the following code:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
var arr = [ 1, 2,,,3, 4 ]; var index = 2; if (typeof arr[index] !== 'undefined' && arr[index] !== null) { console.log("Element exist at the specified index."); } else { console.log("The value at the specified index is undefined."); } /* Output: The value at the specified index is undefined. */ |
Alternatively, you can use the != operator that filters the nullish value.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
var arr = [ 1, 2,,,3, 4 ]; var index = 2; if (arr[index] != null) { console.log("Element exist at the specified index."); } else { console.log("The value at the specified index is either null or undefined."); } /* Output: The value at the specified index is either null or undefined. */ |
3. Check for falsy value
There are 7 falsy values in JavaScript – false, zero (0), BigInt (0n), empty string ("", '', ``), null, undefined, and NaN. The following example uses Type Conversion inside an if block to coerce the value present at the specified index to a Boolean and determine whether the value is falsy:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
var arr = [ 1, 2,,,3, 4 ]; var index = 2; if (arr[index]) { console.log("Element exist at the specified index."); } else { console.log("The value at the specified index is falsy."); } /* Output: The value at the specified index is falsy. */ |
That’s all about checking if an element exists at the specified index in an array in JavaScript.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)