Why doesn't JavaScript warn me when I use arr.lenght (misspelt) instead of arr.length in a loop? I also use strict mode

  • A+

I spent hours just to find out that I misspelt the word .length as .lenght. It can run normally with no warning at all. Why...?

I use 'use strict' and run on Node 10.13.0.


'use strict'; let arr = [1, 2, 3, 4]; for(let i = 0; i < arr.lenght; i++) {   console.log(arr[i]); }


Because when you try to get a property that doesn't exist, it returns undefined, and 0 < undefined is false.

let arr = [1, 2, 3, 4]; console.log(arr.lenght) // undefined console.log(arr.qwerty) // undefined console.log(arr.lenght < 9999) // false console.log(arr.lenght > 9999) // false  arr.length = 7 // <-- it's not a good idea for(let i = 0; i < arr.length; i++) {console.log(arr[i])}


I said 'javascript is not a strongly typed language' and it is true. But this way of adding new properties it is a feature of prototype-based programming, as @Voo said.

I also said .length=7 it's a bad idea. After reading a little more, in this case I still think it's a little weird to increase the length property after adding elements. Maybe it's fine to truncate, delete elements or empty an array, although in the latter case I would prefer arr=[] instead of arr.length=0.

There are some interesting examples about length property in the Mozilla documentation.

A JavaScript array's length property and numerical properties are connected. Several of the built-in array methods (e.g., join(), slice(), indexOf(), etc.) take into account the value of an array's length property when they're called. Other methods (e.g., push(), splice(), etc.) also result in updates to an array's length property.

var fruits = []; fruits.push('banana', 'apple', 'peach'); console.log(fruits.length); // 3 

When setting a property on a JavaScript array when the property is a valid array index and that index is outside the current bounds of the array, the engine will update the array's length property accordingly:

fruits[5] = 'mango'; console.log(fruits[5]); // 'mango' console.log(Object.keys(fruits));  // ['0', '1', '2', '5'] console.log(fruits.length); // 6 

Increasing the length.

fruits.length = 10; console.log(Object.keys(fruits)); // ['0', '1', '2', '5'] console.log(fruits.length); // 10 

Decreasing the length property does, however, delete elements.

fruits.length = 2; console.log(Object.keys(fruits)); // ['0', '1'] console.log(fruits.length); // 2 


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: