JavaScript Variables Notes

From: Core JavaScript 1.5 Guide:Variables – MDC

  1. Declaring a variable without “var” keyword always declares a global variable and generates generates a strict JavaScript warning. So don’t omit the “var” keyword.
  2. JavaScript does not have block statement scope; rather, it will be local to the code that the block resides within.
  3. In JavaScript you can refer to a variable declared later, without getting an exception.
  4. Global variables are in fact properties of the global object. In web pages the global object is window.

Something about “undefined”

A variable that doesn’t have an assigned value is of type undefined. And evaluating such a variable will return undefined.

What is undefined? There’s an answer on MDC.

undefined is a property of the global object, i.e. it is a variable in global scope.

The initial value of undefined is the primitive value undefined.

I’m a bit confused. It’s a property of the global object, so I can change its value at any time.

var a;
document.write(a === undefined); // true
undefined = 3;
document.write(a === undefined); // false

Pity it’s not a keyword like “null”. So don’t rely on it. In my eyes, it’s no different with the variable that doesn’t have an assigned value. See the following code.

var a;
var b;
document.write(a === b); // true
b= 3;
document.write(a === b); // false

I don’t know whether this is described in ECMA specification or not, but I think it would be clearer if undefined was a keyword as null.

So if you really want to test if a variable is undefined, use the typeof operator instead.

typeof a == "undefined"

It’s really a mess.

Leave a comment

Your email address will not be published. Required fields are marked *

Prove your intelligence before hitting * Time limit is exhausted. Please reload CAPTCHA.