array[index] == 'undefined' compares the value of the array index to the string "undefined".
You're probably looking for typeof array[index] == 'undefined', which compares the type.

Answer from deceze on Stack Overflow
🌐
Reddit
reddit.com › r/learnjavascript › checking whether an array element is undefined
r/learnjavascript on Reddit: Checking whether an array element is undefined
September 6, 2022 -

If I am accessing an index of an array based on a variable, I would first want to check that the index exists.

My understanding is that if I try to access an index outside of the array's range, I will get a value of 'undefined.' So,

(typeof array[i] === 'undefined')

should return true if array[i] does not exist.

Would it also be possible, because undefined is falsey, to get the same result with

!array[i]

?

Edit: Thanks for the help!

🌐
freeCodeCamp
freecodecamp.org › news › javascript-check-if-undefined-how-to-test-for-undefined-in-js
JavaScript Check if Undefined – How to Test for Undefined in JS
November 7, 2024 - But we would replace undefined with void(0) or void 0 as seen below: if(typeof user.hobby === void 0){} if(typeof scores[10] === void 0){} if(typeof name === void 0){} ... if(typeof user.hobby === void(0)){} if(typeof scores[10] === void(0)){} ...
🌐
Javatpoint
javatpoint.com › check-if-the-array-is-empty-or-null-or-undefined-in-javascript
Check if the array is empty or null, or undefined in JavaScript - javatpoint
Check if the array is empty or null, or undefined in JavaScript with javascript tutorial, introduction, javascript oops, application of javascript, loop, variable, objects, map, typedarray etc.
🌐
ScratchCode
scratchcode.io › home › check if array is empty or undefined in javascript
Check If Array Is Empty Or Undefined In JavaScript | Scratch Code
December 23, 2020 - So let’s check an array is empty or not. This method has one drawback. If you pass any non-empty string then it will pass the test which is wrong, so for that we have to use Method 2 but to understand Method 2, you should try & test Method 1. <script type="text/javascript"> let devices = [ 'keyboard', 'laptop', 'desktop', 'speakers', 'mouse' ]; // let devices = [ ]; // Try uncommenting this for testing if ( typeof devices !== 'undefined' &&amp; devices.length > 0 ) { alert('array is not empty'); } else { alert('array is empty'); } </script>
🌐
Dmitri Pavlutin
dmitripavlutin.com › 7-tips-to-handle-undefined-in-javascript
7 Tips to Handle undefined in JavaScript
March 23, 2023 - The function returns a new array ... original array. The first version of append(), a bit naive, may look like this: ... Because toAppend object can omit first or last properties, it is obligatory to verify whether these properties exist in toAppend. A property accessor evaluates to undefined if the property does not exist. The first temptation to check whether first ...
Find elsewhere
🌐
EyeHunts
tutorial.eyehunts.com › home › javascript array is undefined | example code
JavaScript array is undefined | Example code
May 29, 2023 - Use length property with the isArray() method to check an array is undefined in JavaScript.
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › undefined
undefined - JavaScript | MDN
// x has not been declared before // evaluates to true without errors if (typeof x === "undefined") { // these statements execute } // Throws a ReferenceError if (x === undefined) { } However, there is another alternative. JavaScript is a statically scoped language, so knowing if a variable ...
🌐
ItSolutionstuff
itsolutionstuff.com › post › how-to-check-if-array-is-empty-or-null-or-undefined-in-javascriptexample.html
How to Check Array Is Empty Or Null In Javascript? - ItSolutionstuff.com
July 4, 2023 - If need for jquery check if array is empty or undefined then i will help you. you can easily check if array is empty or not in javascript. we will use simple if condition and length of array with checking.
🌐
Postman
community.postman.com › help hub
Pm code checking array for undefined element - Help Hub - Postman Community
June 17, 2022 - GET response brings back a certain number of elements. Have an array, sized with expected number of elements anticipated. So we walk through the GET response (for-loop), checking each element in the GET response for specific data depending on data in that element of the response (if field1=“xy” then check this value and that value) and putting the ‘key’ value (field1) into the array allocated earlier.
🌐
Stack Overflow
stackoverflow.com › questions › 28709580 › check-for-undefined-array
javascript - Check for undefined array - Stack Overflow
Now, i have a for loop which iterates ... with index greater than 4. How do i check for this condition. ... if (typeOf questArray[noCoun][0]['q_sec'] !== undefined){ if (secCnt == questA...
🌐
Board Infinity
boardinfinity.com › blog › how-to-quickly-check-if-an-array-is-empty-or-not-in-javascript
Check if Array is Empty or Not-Javascript | Board Infinity
July 9, 2023 - The Array.isArray() method can be used to determine whether an array is actually there and whether it exists. If the Object supplied as a parameter is an array, this function returns true.
🌐
Latenode
community.latenode.com › other questions › javascript
How can I verify if an array is empty or undefined? - JavaScript - Latenode Official Community
October 10, 2024 - What is an efficient method to determine if an array is either empty or undefined? Is this a viable way to check this? if (!array || array.length === 0) { // array is empty or doesn't exist }
🌐
Medium
medium.com › front-end-weekly › beginners-guide-dealing-with-undefined-in-javascript-d98ac7e413db
Beginner’s Guide: Dealing with Undefined in JavaScript | by Brandon Evans | Frontend Weekly | Medium
June 8, 2023 - In the above example, we use includes() to check if the arr array includes the value undefined. It returns true because undefined is present in the array. The void operator in JavaScript allows you to evaluate an expression and always return ...
Top answer
1 of 3
4

The array what you created is called a sparse array. You can read more about it in this answer.

The check

if (field !== undefined)

might not help if the actual value stored in the array itself is undefined. And this check

if (field)

will evaluate to be truthy if field is any one of the Truthy values. You can read more about the Truthiness and Falsiness of different values in this answer.

So, if you want to know if the array has a particular index, then you can use Object.prototype.hasOwnProperty, like this

var array = [];
array[1] = undefined;

console.log(array[0]);
// undefined
console.log(array[1]);
// undefined
console.log(array.hasOwnProperty(0));
// false
console.log(array.hasOwnProperty(1));
// true

Here the element at 1 is defined to be undefined, but since 0 is not defined at all, by default, JavaScript returns undefined.

The hasOwnProperty call checks if the current object really has the index 0 and 1.

2 of 3
2

"Best" is a fairly subjective term, so let's throw some objective criteria at it:

  1. Which is faster?

    In a way that you'll notice in the real world, neither. But if you really want to know, measure your specific code on the engines you want to support.

  2. Which is easier to read?

    This is probably subjective as well. The second form is extremely common in JavaScript, FWIW.

  3. Which is less typing?

    The second form is obviously a lot shorter than the first.

  4. Which is more reliable?

    Given your use case, they're equally reliable, because you're either not storing an entry in the array at all, or storing a non-null object reference.

    In similar but different use cases, you might need to be wary of the difference: The first form will only be true for an entry that exists and doesn't have the value undefined in it. The second form will be true for anything that isn't falsey. There are several falsey values: null, undefined, 0, "", NaN, and of course, false. So you wouldn't use the second form to decide whether there was a number at a position in the array, since 0 is a number but if (0) won't go into the body of the if.

    Speaking of ambiguity, note that comment about "...true for an entry that exists and doesn't have the value undefined in it..." Neither of the examples you gave differentiates between an entry that doesn't exist and an entry that exists with the value undefined. If you need to differentiate those at some point (again, not for the use case you mentioned), you'd use hasOwnProperty on the array: if (array.hasOwnProperty(row))

The second solution is shorter, so it could be quicker to execute, because JavaScript is an interpreted scripting language

This is a mistaken assumption. Most modern JavaScript engines are just-in-time optimizing compilers. V8 (the engine in Chrome), for instance, is a two-stage optimizing compiler: On the first pass, it turns your JavaScript into machine code quickly, and then if it identifies hotspots (bits of code that run a lot), it goes back and does more aggressive optimization there.