Skip to content Skip to sidebar Skip to footer

Can I Trust Elements From A New Array To Equal To False?

In the browsers I tested, var a = new Array(5); will return an Array of 5 undefined elements. Since undefined equals to false I can consider my array to be initialized with false e

Solution 1:

When you initialize an array in Javascript it has no elements, i.e. nothing is present in any position unless you put something there. The only thing you have is length set to the number you specify.

When you access the element by reading it and nothing is there then you get undefined (as it happens when you acces a member of an object that doesn't exist).

Note however that an element that is not present at all is not exactly the same as an element that is set to undefined. For example:

var x = new Array(5);
console.log(x[2]);                 // ==> Output is "undefined"
console.log(x.indexOf(undefined)); // ==> Output is "-1" (not present)
x[2] = undefined;
console.log(x.indexOf(undefined)); // ==> Output now is "2"

If you only care about whether an element will be considered true when placed in an if then the array appears at a first sight to contain undefined that is false in that context.

Note however that even what is false or true is quite a subtle concept in Javascript, especially because of automatic conversions... for example

console.log([] ? 1 : 2);  // Output is "1", an empty array is "true"
console.log([] == false); // output is "true" (so it's also equal to false!)

Solution 2:

You do not have to initialize your array for this to work.

var array = [];
console.log(array[0]); // undefined
console.log(!!array[0]); // false (undefined is _falsy_)
array.push("foo");
console.log(array[0]); // "foo"
console.log(!!array[0]); // true ("foo" is _truthy_).
array[1] = "bar";
console.log(array[1]); // "bar"
console.log(array.length); // 2

Solution 3:

The undefined value does not "equal" to false, it's just considered falsey when you test it like if(undefined).

Whether it's safe or not, it really depends on the code you're using it on. If you want to check if value is really false, you should use strict equality and check if(val === false), so you don't mistake it for any other falsey value.

You can also check the typeof the variable to make sure it's what you expect:

typeof false;      // "boolean"
typeof undefined   // "undefined"

Post a Comment for "Can I Trust Elements From A New Array To Equal To False?"