All arrays in JavaScript contain array.length
elements, starting with array[0]
up until array[array.length - 1]
. By definition, an array element with index i
is said to be part of the array if i
is between 0
and array.length - 1
inclusive.
That is, JavaScript arrays are linear, starting with zero and going to a maximum, and arrays don't have a mechanism for excluding certain values or ranges from the array. To find out if a value exists at a given position index (where index is 0 or a positive integer), you literally just use
if (index < array.length) {
// do stuff
}
However, it is possible for some array values to be null, undefined
, NaN
, Infinity
, 0, or a whole host of different values. For example, if you add array values by increasing the array.length
property, any new values will be undefined
.
To determine if a given value is something meaningful, or has been defined. That is, not undefined
, or null
:
if (typeof array[index] !== 'undefined') {
or
if (typeof array[index] !== 'undefined' && array[index] !== null) {
Interestingly, because of JavaScript's comparison rules, my last example can be optimised down to this:
if (array[index] != null) {
// The == and != operators consider null equal to only null or undefined
}
manpreet
Best Answer
2 years ago
Will this work for testing whether a value at position "index" exists or not, or is there a better way: