Skip to content Skip to sidebar Skip to footer

Variable Scope And Var

It all started with these simple lines of code: a = 3; b = 2; function line(x) { var a = 5; var b = 4; return a*x+b; } // returns 17 b = line(a) - b; alert(b); // r

Solution 1:

var creates a local variable, scoped to the function in which it appears. Any variable that is declared in the global scope becomes a property of the global object (in a browser, window), and any variable referenced in a function which is not declared with var in that function refers to the surrounding scope, quite possibly the global scope.

There is also a new keyword, let, which is coming in the upcoming version of ECMAScript and is already in some browsers, which creates a block-scoped variable.

So, in your first example (I am going to assume this is running in a browser), you create window.a and window.b which are bound to 3 and 2, respectively. Function line declares local variables a and b. When window.a is passed to line, the parameter x is bound to the value 3 (the value of window.a). Local variables a and b are 5 and 4, respectively. These have nothing to do with window.a and window.b. The calculation a*x+b is, thus, 5*3+4, or 19.

The code b = line(a) - b passes window.a to line, calculates the value 19, subtracts the current value of window.b from it (2), resulting in 17, which is then assigned to window.b. The value of 36 comes from line(3) (which is still 19) plus 17 (the new value of window.b).

When you removed the var from the assignment to b in function line, you changed it so that b is no longer a local variable. In that case, all references to b in the function refer to the global value window.b.

In the case of your Riddle #2, where you got 23, after the first call window.b is equal to 15. When line(a) is called a second time, window.b is set back to 4, the a*x+b calculation still gets 19, and then window.b (4) is added again, making 23.

It is important to note that the var keyword declares a variable that is function-scoped, not block-scoped as you might expect from other C-derived languages. For example, in this function:

functionscope(array) {
    var a = 7;

    for (var b = 0; b < array.length; ++b) {
        var c = array[b];
    }

    alert(a + b + c);
}

All the variables have scope which extends over the entire function. In particular, the scope of c is not limited to the for loop.

A variable that is not declared in a particular scope doesn't necessarily reference a global variable, however. If it is nested inside another function scope, it will refer to that nested scope. Consider the following example:

var b = 7;

function outer() {
    var b = 42;

    function inner() {
        return b; // refers to b in outer, not global
    }

    return inner();
}

alert(outer()); // 42, not 7

Solution 2:

The variable declared without var is global variable, this is the rule. But remember if you want to declare multiple local variable with one var, separate them with comma.

var a = 5; //local variable
    b = 4; // global varialbe

var a = 5, //local variable
    b = 4; //local varialbe

Solution 3:

VAR declares a new instance in memory for a new variable. Simply saying b = 4 will try to change the value of b to 4. If b has not been initialized nothing will happen.

This ties into the concept of PRIVATE and LOCAL variables, and naming conventions.

Firstly, you have 2 variables called a and 2 called b. This is bad practice because you might change the value of the other one by mistake, or its old value could still be sitting in memory because it was already initialized and given a value. Remember, you do not always NEED to assign a value when initializing, it's just best practice.

Secondly, your function can modify a variable from the level above it. In other words, by taking away VAR on that one line it's possible to modify the original value of b which you set to 2 at the beginning of the file.

TLDR; Don't use the same variable name more than once, and always use your VAR when trying to make a NEW variable.

Solution 4:

If you're in the global scope then there's no difference.

If you're in a function then "var" will create a local variable, "no var" will look up the scope chain until it finds the variable or hits the global scope (at which point it will create it).

Source

In the case of your first function, line(a) is processed first, and by the time it runs, you've set b = 4. Therefore, and because b is a globally defined variable, when it runs line(a) - b, you're getting:

line(a) (returns 19)

And minus b (b = 4)

19 - 4 = 15

You can simplify your statement and get the same result:

//define global variable bvar b = 2;
functionline(x) {
    //x = 3//update global variable b; it now = 4
    b = 4;
    //forget the math and just return 19return19;
}

//run function; before, b = 2, after b = 4
b = line(3) - b;
alert(b);

Likewise with your second example, because your function changes the value of global variable b, the only difference is that you're adding 4 instead of subtracting (19 + 4 = 23).

To avoid this confusing nature of variables, always be careful to differentiate between global and local variables whenever possible, and only drop var when you need to explicitly update global variables in functions. In actual fact too, since global variable always remain in memory, you should use globals only when you explicitly need them. Here's an unambiguous example:

var globalVar;
functionsomeFunc(x) {
    var tempVar = 4;
    return x * tempVar;
}

Post a Comment for "Variable Scope And Var"