2

I'm reading a book on JavaScript called Eloquent JavaScript. The following is a snippet from the book:

"The two main ways to access properties in JavaScript are with a dot and with square brackets. Both value.x and value[x] access a property on value—but not necessarily the same property. The difference is in how x is interpreted. When using a dot, the word after the dot is the literal name of the property. When using square brackets, the expression between the brackets is evaluated to get the property name. Whereas value.x fetches the property of value named “x”, value[x] tries to evaluate the expression x and uses the result, converted to a string, as the property name."

While playing around with this bit of information, I happened to try this bit of code. It returns the value at the first index of the array. Why so?

arr = [1,2,3];
len = "length";
console.log(arr[len]);

// Output is "3" as expected

arr = [1,2,3];
console.log(arr.length);

//Output is "3" as expected

arr = [1,2,3];
len = "length";
console.log(arr[length]);

//Output is "1"

//The output I was expecting was an error or at least the value "3" since JS is a flexible language.

tinuggunit
  • 39
  • 6

3 Answers3

5

Because the zeroth element of arr is 1

i.e. you probably meant to do this

arr[len]

length itself is zero, hence the you are really doing this arr[0]

length is window.length, which this link explains

https://www.w3schools.com/jsref/prop_win_length.asp

(Added later)

The confusion seems to be around length being the same as window.length. The links below may help with understanding that, although if you're a beginner I'd probably just accept it and return to it later

window.variableName

Difference between variable declaration syntaxes in Javascript (including global variables)?

tony
  • 2,178
  • 2
  • 23
  • 40
3

You can't use variable names as strings.

length has a value of 0 (because it is the same as window.length, which actually represents the number of frames in the current document), so you're seeing the first element of the array:

let arr = [ 1, 2, 3 ];
console.log( length );      // 0
console.log( arr[length] ); // 1
BenM
  • 52,573
  • 26
  • 113
  • 168
2

You take the length, which is a property of Window and returns the number of frames of the window.

console.log(length); // 0
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392