6

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

Rahul
  • 2,309
  • 6
  • 33
  • 60
Tukhsanov
  • 301
  • 1
  • 3
  • 15
  • That's easy, don't give them the same name. – adeneo May 17 '14 at 10:31
  • @adeneo is 2nd variable is being overwrited? I think, in c++ this code will work fine, nope? There are local variables and global variables in c++ and they have different scope, nope? – Sharikov Vladislav May 17 '14 at 10:31
  • 1
    @adeno i want to know is it possible? – Tukhsanov May 17 '14 at 10:32
  • Why would you reassign it, if you want to use its initial value? Does not make sense. – Artyom Neustroev May 17 '14 at 10:33
  • @Artyom Neustroev i'm learning javascript and jquery and i simply playing with codes and and i wanted is it possible or not. thank you – Tukhsanov May 17 '14 at 10:35
  • 1
    It's not possible, an if statement has no special scope, so you can't have two variables with the same name within the same scope and access both, the latter will overwrite the former, so they should have different names. – adeneo May 17 '14 at 10:42
  • @adeneo I just got this too. I thought if has its own scope. Explanation in [this](http://stackoverflow.com/a/23710318/2898694) answer. Thank you too :) – Sharikov Vladislav May 17 '14 at 10:44

10 Answers10

5

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.

the6p4c
  • 644
  • 5
  • 17
5

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);
}
Pankaj
  • 99
  • 6
  • 1
    Using window.varname is just bad design. Yes it works, but no you shouldn't do it. If you REALLY insist on doing something like that at least create some other object in the global space and use it instead of window for this. – Brendan F May 24 '14 at 19:20
4

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

the6p4c
  • 644
  • 5
  • 17
3

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

Balachandran
  • 9,567
  • 1
  • 16
  • 26
3

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.

Community
  • 1
  • 1
Chris Wesseling
  • 6,226
  • 2
  • 36
  • 72
2

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.

1

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

TheGr8_Nik
  • 3,080
  • 4
  • 18
  • 33
1

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

nettux
  • 5,270
  • 2
  • 23
  • 33
1
var abc = new Array();
abc[0] = 'str1';
abc[1] = 'str2';

Use array in this case

Rohit Batham
  • 1,238
  • 1
  • 9
  • 13
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/

guest271314
  • 1
  • 15
  • 104
  • 177