Skip navigation

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 !!!

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: