Sunday, December 26, 2010

Little known behavior on Javascript.

Most of us know that when we declare variable without using "var" keyword that variable will get defined in global scope and will be available to be called any where in the Javascript program. But look at the following code:

name="Ravi"

function nm(){

    alert(name)

    var name="Kavi";

    alert(name)

}

nm()


When you run this code in a browser you expect to see 2 alerts and one with name "Ravi" and another with name "Kavi". But for your surprise you get "undefined" in the first alert. You know why? This is the unique behavior off Javascript. in your function irrespective of where you use "var" keyword code will get parsed as if you have that variable declared in first line of the function. Hence it's good practice to declare all variables on the top, so that your code looks and works same way. 

No comments:

Post a Comment