Tukhsanov Tukhsanov - 1 month ago 6
Javascript Question

Declaring two variable with the same name

Is it possible to call the same name variables which set outside of the function?

var a = $(window).width(); // I want to call this variable
if(!$.isFunction(p)){
var a = $(window).height(); // Not this one
alert(a);
}


FIDDLE

Answer

In a code snippet such as yours, the variable a is being redefined. This is because an if statement doesn't create another scope for variables. However, functions do.

In a case like this:

var a = 0; // global
function doStuff() {
    var a = 10; // local
    alert(a);
    alert(window.a)
}
alert(a);
doStuff();
alert(a);

inside the function doStuff, the variable a is being redefined. This snipped will therefore alert the numbers 0, 10, 0, 0. This proves that the global variable is not redefined inside the function, as printing a after calling doStuff doesn't change the value of a in the global scope.

The variable a outside of the function can be accessed, as any variable not declared in a non-global scope is placed inside the window object. However, if using this snippet (which calls an anonymous function, creating a new scope):

var a = 0; // global
function doStuff() {
    var a = 10; // local
    alert(a);
    alert(window.a)
    function() {
        var a = 20; // even more local
        alert(a);
        alert(window.a);
    }();
}
alert(a);
doStuff();
alert(a);

you cannot access the value of a inside the doStuff function. You can still access the global variable using window.a.

In your case, however, the if statement does not create a new scope, therefore you are redefining the variable a to the new value $(window).height().