Wednesday, August 15, 2012

Scope of variables in javascript

In this post i will explain  how to declare and access of javascript variables.If a variable is declared inside of a function with "var" then it is local variable.
var a;-->//global
function f1()
{
//logic
}
If a variable is declared outside of a function with "var" then it is global variable.If a variable is declared implicitly any where in the code then it is global unlike other languages.
function f2()
{
var a; -->//local variable .It can access only this function
c=10;-->implicitly created.That's why global
}
We can redefine a global variable locally by declaring global variable again inside a function .Inside a function any reference will redirect to local variable only,we can use this keyword to refer global variable like this a=10;||refer to global a
function f3()
{
var b;//redefined
}

No comments:

Bel