Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

typeof name returns string even though number was assigned

This is really tearing apart my JS concept. What's wrong at all here?

const NAME = 'chusss';
var name = 123;
console.log(typeof name); // string, wasnt it supposed to print number?
console.log(name); // 123
like image 458
aitchkhan Avatar asked Mar 07 '23 11:03

aitchkhan


1 Answers

The name variable actually belongs to window.name which lets you set the name of the window.

From MDN

The name of the window is used primarily for setting targets for hyperlinks and forms.

Further down it's written:

Don't set the value to something unstring since its get method will call the toString method.

Thus you always get a string returned.


If you still want to use the name variable but dont want to have the collision with window.name, then wrap your code inside a immediate invoked function expression (IIFE) and benefit from the functional scope.

Demo

(function() {
  var name = 123;
  console.log(typeof name);
  console.log(name);
})();

If you run this code in node.js you won't observe that behaviour as name is not a property of the global object and thus not defined in global scope.

like image 131
Kristianmitk Avatar answered Mar 15 '23 00:03

Kristianmitk