Tukhsanov
Tukhsanov

Reputation: 303

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

Upvotes: 6

Views: 19133

Answers (10)

Chris Wesseling
Chris Wesseling

Reputation: 6368

There is no blockscope in JavaScript (at least up until ES6).

Like you seem to expect from the if block. See What is the scope of variables in JavaScript? for an excellent summary of scopes that do exist in JavaScript.

Beware of Hoisting

Furthermore, you shouldn't sprinkle your var declarations through your code, but explicitly put them in the top of your function. That is where Javscript will hoist them anyway:

# so if you have a function like this


var i = 5;
function testvar () {
     alert(i);
     var i=3;
}
testvar();


# the alert window will contain undefined. 
# because internally, it's been changed into this:


var i = 5;
function testvar () {
     var i;
     alert(i);
     i=3;
}
testvar();

Minimize use of the global scope

Read What is meant by “leaking” into global scope?

And listen to what Doug Crockford has to say about it. Actually, take an hour and watch the whole talk.

Upvotes: 3

guest271314
guest271314

Reputation: 1

Try this (pattern)

var p = ['foo', ''];
var a = function (name) {
    return (
           name === "height" 
           ? $(window).height() 
           : (name === "width" ? $(window).width() : name)
           )
};
if (!$.isFunction(p)) {
    // `$(window).width()` , `$(window).height()`
    alert( a("width") + "\n" + a("height") );
}

jsfiddle http://jsfiddle.net/guest271314/2tuK4/

Upvotes: 1

the6p4c
the6p4c

Reputation: 664

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().

Upvotes: 4

MasqueradeCircus
MasqueradeCircus

Reputation: 854

You can do it like this:

var p = ['foo',''];
var a = $(window).width(); // I want to call this variable
if(!$.isFunction(p)){
    (function(b){
        var a = $(window).height();
        alert(b);
    })(a);
}

No need to use the global scope, just create an anonymous function and call it with a as the argument. Inside the function b is a reference to the a variable outside the function.

It is a good practice not to modify the window object in javascript to write clean and maintainable code.

Less bugs and problems. I mean, never do the window.a thing. Is evil for your code.

Upvotes: 2

user5296864
user5296864

Reputation:

var abc = new Array();
abc[0] = 'str1';
abc[1] = 'str2';

Use array in this case

Upvotes: 1

nettux
nettux

Reputation: 5406

JavaScript has two scopes: global and local. In your example a is in the global scope both times so you are just redefining it.

However you can specify skip a variable in local scope and get the one from global. Consider this example:

var  a = 1;

function foo () {
    var a = 2;
    console.log("var a is: " + window.a);
    console.log("local var a is: " + a);
}

foo ();

Will log "var a is: 1"\n"local var a is: 2\n" to the console. This is about as close as it gets to what you need

Upvotes: 1

TheGr8_Nik
TheGr8_Nik

Reputation: 3200

No, you can't because of you have redefined the variable name in the same scope and beacuse of the hoisted variables your code will be interpreted by javascript in the following mode:

var p, a; 

p = ['foo',''];
a = $(window).width(); // I want to call this variable

if(!$.isFunction(p)){
  a = $(window).height(); // Not this one
  alert(a);
}

Now you can easly see that the variable a will be replaced and not created

Upvotes: 1

Pankaj
Pankaj

Reputation: 99

If you want to declare a global variable you can do so by

window.varname="This is a global variable";

And you can access the same by

alert(window.varname);

Now you can also have a local variable inside a function with the same name

var varname="This is a local variable";

And you can access it normally.

Here's your code so that you can access the global variable not the local one.

var p = ['foo',''];
window.a = $(window).width();
if(!$.isFunction(p)){
    var a = $(window).height();
    alert(window.a);
}

Upvotes: 5

Balachandran
Balachandran

Reputation: 9637

Example:

var a=10;

if(true){
    var a=5;
}

alert(a)// it will return a=5;

var a=10;
var a=5;

//both are same way assign value 

In js if statement is not scope it visible every where with in function . you have to change the variable name

Upvotes: 3

the6p4c
the6p4c

Reputation: 664

In this case, you have actually redefined the value of a. There is absolutely no way of referencing a different variable with the same name, as it just acts as a redefinition.

Upvotes: 5

Related Questions