2

I'm not new in javascript but i don't understand this behaviour at all.

Why a variable named "name" is typed as string only ? Its a new ES6 feature ??

var name = 56;
console.log(name, typeof name);
name = function(){console.log("ok");}
console.log(name, typeof name);
Daphoque
  • 4,421
  • 1
  • 20
  • 31
  • `name` is an property on `window` object, don't use that as variable in global scope, use any other name you will not see this behaviour – Code Maniac Jun 07 '19 at 09:41
  • because window.name is a global variable. – enno.void Jun 07 '19 at 09:41
  • 5
    Possible duplicate of [Using the variable "name" doesn't work with a JS object](https://stackoverflow.com/questions/10523701/using-the-variable-name-doesnt-work-with-a-js-object) and [Javascript, var name = 1, “typeof name” gives “string”?](https://stackoverflow.com/questions/29360290) and [var name produces strange result in Javascript](https://stackoverflow.com/questions/20945498) – adiga Jun 07 '19 at 09:41
  • i understand it's a global variable, i just didn't understand why all values are converted to string, according to developer.mozilla its not a bug its a feature. I didn't know this at all, is it possible to force variable type like this ? or this is defined in the core engine ? – Daphoque Jun 07 '19 at 09:50
  • 1
    @Daphoque you will find [this one](https://stackoverflow.com/a/21396286/9624435) helpful – Code Maniac Jun 07 '19 at 09:51
  • @Daphoque [MDN](https://developer.mozilla.org/en-US/docs/Web/API/Window/name#Notes) clearly states that it converts all the value to their string representation using `toString` – Code Maniac Jun 07 '19 at 09:54
  • Yeah i see that :) When you first see this and you're not aware of it it's quite strange. Thanks everyone i will sleep less stupid tonight :D – Daphoque Jun 07 '19 at 09:56
  • @Daphoque this will help you more [Browsing context name](http://w3c.github.io/html/browsers.html#browsing-context-name) – Code Maniac Jun 07 '19 at 09:57

1 Answers1

3

name it's a property of global object window and you cant replace it.

But you can delete and then define again

delete window.name;

window.name = ()=>{console.log('ok')}

But i don't recommend change global properties.

In node environment all work good:

enter image description here

Vadim Hulevich
  • 1,803
  • 8
  • 17