Ad

Javascript Substring Method Support For Interger - Chrome

When I try to assign number value to JavaScript keyword name as like below

var a="12345";
var b=a.substring(1,3)
console.log(b);
var name=12345;
var y=name.substring(1,3)
console.log(y);

I excepted it to throw the type error, but it produces the same output for variable b and name.

I'm aware that keywords should not be used as variable, still curious to know how it works.

Ad

Answer

name refers to window.name, a string (which looks to be enforced by browsers).

When you write var name = 12345; you basically overwrite it (due to how var works, see differences betwen var and let).

Since window.name must hold a string, it's therefore converted to '12345' internally.

Ad
source: stackoverflow.com
Ad