I found this weird problem, when I write Javascript code like below:
var name = 1;
alert(typeof name); // this will alert "string"
var b = 1;
alert(typeof b); // this will alert "number"
I got "string" for "typeof name", but got "number" for "typeof b", however, I think they both should be "number"
And this code won't run either:
var name = 1;
if (name === 1) {
alert("ok")
}
It won't alert out, since name's type is "string" !
I tested above code in Chrome and Safari, they both give the same result, so why "typeof name" is "string" in this case? why the variable name "name" is so special?
It is a behavior of the browser where some properties of window object like name and status will take only string values, if you assign any other type of values then the toString() value of that object is assigned to it
var name = 1;
console.log(typeof name); // this will alert "string"
var status = 1;
console.log(status, typeof status); //gives '1` and string
var status = {};
console.log(status, typeof status);//gives value of status as [object Object] since that is the toString() implementation of object
var b = 1;
console.log(typeof b); //
Demo: Fiddle
This behavior is not applicable if you use local variables... ie variables in a function
function test(){
var name = 1;
console.log(typeof name); // this will alert "string"
var status = 1;
console.log(status, typeof status); //gives '1` and string
var status = {};
console.log(status, typeof status);//gives value of status as [object Object] since that is the toString() implementation of object
var b = 1;
console.log(typeof b); //
}
test()
Demo: Fiddle
The reason is that there is a property under window
named name
(window.name
) and it is already defined as a string.
When you declare a variable with no scope, it's scoped under window
.
Check more about window.name
.
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