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 elements as long as I test them this way:
if (a[0]) console.log("the element is no longer falsy");
else a[0] = true;
Is it a safe way to initialize an Array with false values or is it just a hack that should be avoided?
EDIT: my goal is to have it initialized to falsy values as in my example. I want to make sure that new Array() is a trustworthy way to do so.
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
lengthset 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:If you only care about whether an element will be considered
truewhen placed in anifthen the array appears at a first sight to containundefinedthat isfalsein that context.Note however that even what is
falseortrueis quite a subtle concept in Javascript, especially because of automatic conversions… for example