DEV Community

Discussion on: Kyle Simpson proved I STILL don't know JavaScript (arrays)

Collapse
 
blindfish3 profile image
Ben Calder

Like I said - this isn't something I tend to dig into too much...

But I think we're more or less in agreement - I'm just not comfortable with the idea of a distinction between explicit/implicit undefined. However you get to it undefined === undefined :D

I didn't dig into the spec but did think to do this:

var array1 = [,"a","b"];
// since an Array is just a fancy Object:
console.log(Object.keys(array1)); // ["1", "2"]
console.log(array1.hasOwnProperty(0)); // false
console.log(array1.hasOwnProperty(1)); // true
console.log(array1.hasOwnProperty(2)); // true

// seems obvious but for ... of isn't the only way to 
// get the implicit undefined
for(let i = 0; i<array1.length; i++) {
  console.log(array1[i]);
} // undefined a b

array1[0] = "c";
console.log(Object.keys(array1)); // ["0", "1", "2"]

// and just for good measure:
console.log(Object.keys([,"a",,,"b",])); // ["1", "4"]

So the above suggests that:

  • keys are only set for values that are explicitly declared
  • modern iterator functions loop over Object.keys - i.e. enumerable properties
  • for ... of assumes that Object.keys should conform to array standards (i.e. start at 0 increment by 1)
  • the old fashioned for loop just does what you tell it :)
  • undefined is always returned when you try to access an object property that doesn't exist

Thanks for the article! It turns out that thinking about what happens under the hood can consume far too much of my time :D

Thread Thread
 
paceaux profile image
Paceaux

I updated my article to reflect our conversation (seemed too useful not to)

I think this goes back to an odder quirk of JavaScript where sometimes undefined also means "undeclared", but not always.

this "implicit undefined" is really more like an "undeclared", but JavaScript doesn't provide a means to distinguish the two very easily.