5

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?

Bo Tinker
  • 195
  • 1
  • 2
  • 6
  • but it works like charm(properly) -> http://jsfiddle.net/s2tnns49/1/ – Pratik Joshi Mar 31 '15 at 03:53
  • 2
    In browsers, the [global `name`, or `window.name`](https://developer.mozilla.org/en-US/docs/Web/API/Window/name), is already defined to always be a string. – Jonathan Lonowski Mar 31 '15 at 03:53
  • 1
    @jQuery.PHP.Magento.com not really... see below – Arun P Johny Mar 31 '15 at 03:58
  • 1
    @jQuery.PHP.Magento.com Note that JSFiddle's `onLoad` option wraps the code in an event handler, adding an additional scope for local variables that won't clash with predefined globals. – Jonathan Lonowski Mar 31 '15 at 03:58
  • 1
    @jQuery.PHP.Magento.com your example is working because it is in a window onload handler so it is not a global variable - http://jsfiddle.net/arunpjohny/s2tnns49/2/ – Arun P Johny Mar 31 '15 at 03:59
  • @jQuery.PHP.Magento.com Thanks, try put your code inside a – Bo Tinker Mar 31 '15 at 04:00

2 Answers2

10

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

Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
4

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.

Ravan Scafi
  • 6,382
  • 2
  • 24
  • 32