2

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.

Daniel
  • 10,641
  • 12
  • 47
  • 85
rajesh kumar
  • 1,578
  • 16
  • 14
  • JS does not care about the type means not strongly typed, so when you write name.substring , js does not know if its a string,int or object. at run time its just parse it to string and do the function. the same is true when you try to add 1+"123", it wil lgive you 1123 not error – Atul Aug 18 '18 at 12:18
  • That is why now a days people use typescript to avoid such scenarios. – Atul Aug 18 '18 at 12:19
  • 2
    `name` is `window.name` which is always a string. @Atul you can't use substring on a Number-typed variable. Note that using `let` instead of `var` would allow you to redefine that variable. – Jeto Aug 18 '18 at 12:20
  • @Jeto the question is why its not throwing an error, that what i was explaining. – Atul Aug 18 '18 at 12:21
  • @Atul If you replace `name` with anything else in his 4th line you'll get an error. The reason it's not throwing one is because `var name = 12345` does not create an integer variable because it overwrites `window.name` which is a string (and has to be one). – Jeto Aug 18 '18 at 12:22
  • @Jeto understood , thanks. – Atul Aug 18 '18 at 12:28

1 Answers1

3

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.

Jeto
  • 14,596
  • 2
  • 32
  • 46