Skip navigation

Monthly Archives: November 2010


Global variable in JavaScript is bad. Even if you aware of this, you may end of with some global variable accidentally. Consider the code below

// function definition
function foo(){
  // variable declaration and initialisation
  var a, b = 0;
}

here b is global because

// JavaScript will interpret as follows
var a = (b = 0);

Variable declaration only goes to variable a but not b. So here the variable b becomes global. A better solution would be

// declare both first
var a,b
// assign values after
a=b=0;

Is it helpful? đŸ™‚


Here is the code for creating scope inside if block.

function foo() {
  var x = 1;
  if (x) {
    (function () {
      var x = 2;
      // some other code
     }());
  }
  // x is still 1.
}

If it is strange to you, here are some clues

var foo = 1;
function bar() {
  if (!foo) {
    var foo = 10;
  }
  alert(foo);
}
bar();

If it surprises you that the answer is “10”? Here goes another

var a = 1;
function b() {
  a = 10;
  return;
  function a() {}
}
b();
alert(a);

is it terrified to see the browser alert “1”? here goes last one…

Try the following in Firebug:

var x = 1;
console.log(x); // 1
if (true) {
  var x = 2;
  console.log(x); // 2
}
console.log(x); // 2

This is because JavaScript has function-level scope.
One more concept is variable hoisting. The simplest example is

function foo() {
  bar();
  var x = 1;
}

is actually interpreted like this:

function foo() {
  var x;
  bar();
  x = 1;
}

I know, this post will not give you fair idea what Im talking about. But run the code in firebug, if you are curious, please dig on these keywords in google javascript hoisting, javascript scope.

The main purpose of this post is to invoke your curiosity. Happy JavaScripting !!!