javascriptconsolestring-lengthmisspelling

Why wrong spelling in str.length doesn't show an error in JS


I'm a beginner javascript dev, I wrote this code:

var foo = "sunny";
var longitudInt = foo.length;
console.log("The length of " + foo + " is " + longitudInt);

But when I wrote foo.length, I made a spelling mistake and wrote foo.lenght, but it didn't show an error in the console, Why? It doesn't show an error


Solution

  • foo.lenght will not raise an error but it will return undefined. The reason for this is that foo is a String type variable and when it try to call the property lenght (which is invalid), it does not get that in its prototype. Thus, it returns with undefined instead of error.

    var foo = 'str';
    console.log(foo.lenght);

    However, if you try to access other properties in foo.lenght say, foo.lenght.len then this will give you error because at this time foo.lenght is undefined and it tries to read a property of a undefined type.

    var foo = 'str';
    console.log(foo.lenght.len);