Aracthor
Aracthor

Reputation: 5907

Best way to check undefined element in an array

I have an array linking integers to objects:

var array = [];
array[3] = new Something();
array[42] = new OtherSomething();
array[84] = new SomethingAgain();

I want to check if an field exists in an array, and then use it if it does.

var field = array[row];

If the array doesn't contain any field with index row, then field will be set to undefined.

My question is: what is the best way to check its existence between:

if (field !== undefined) { /* Do stuff with field */ }

And:

if (field) { /* Do stuff with field */ }

The second solution is shorter, so it could be quicker to execute, because JavaScript is an interpreted scripting language. But in another hand, it might check for boolean value of field, or something like that...

What is your point on this ?

Upvotes: 2

Views: 1947

Answers (3)

Lewis
Lewis

Reputation: 14866

I'll give you this example. Hope it helps you feel clearer.

var arr = [];
arr[0] = 0;
arr[1] = undefined;
arr[2] = null;
arr[3] = NaN;
arr[4] = '';
arr[5] = false;

arr[11] = 1;
arr[12] = [];
arr[13] = {};
arr[14] = 'hello';  
arr[15] = true;  

if(arr[0]) //false but exists
if(arr[1]) //false but exists
if(arr[2]) //false but exists
if(arr[3]) //false but exists
if(arr[4]) //false but exists
if(arr[5]) //false but exists

if(arr[6]) //false and not exist
if(arr[7]) //false and not exist
if(arr[8]) //false and not exist
if(arr[9]) //false and not exist
if(arr[10]) //false and not exist  

if(arr[11]) //true and exists
if(arr[12]) //true and exists
if(arr[13]) //true and exists
if(arr[14]) //true and exists
if(arr[15]) //true and exists

In general, I recommend you to use the second solution for checking existence since it's shorter and easier to read. However, it still strongly depends on your case. Make sure that your choice is not going to fail in any unexpected situations.

Upvotes: 2

T.J. Crowder
T.J. Crowder

Reputation: 1074238

"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.

Upvotes: 2

thefourtheye
thefourtheye

Reputation: 239463

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.

Upvotes: 4

Related Questions