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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With