Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript, var name = 1, "typeof name" gives "string"? [duplicate]

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?

like image 303
Bo Tinker Avatar asked Mar 31 '15 03:03

Bo Tinker


2 Answers

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

like image 200
Arun P Johny Avatar answered Nov 03 '22 00:11

Arun P Johny


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.

like image 27
Ravan Scafi Avatar answered Nov 03 '22 00:11

Ravan Scafi