lukas.pukenis
lukas.pukenis

Reputation: 13597

What are advantages of predefining variable in global scope?

Often I come in a situation where I act according to my mood:

Situation A):

 function a() {
     var msg = 'a()';
     ..operate on msg
   }

   function b() {
     var msg = 'b()';
     ..operate on msg
   }

Situation B):

var msg;
function a() {
  msg = 'a()';
 ..operate on msg
}

function b() {
  msg = 'b()';
 ..operate on msg
}

Note that with "operate on msg" I do not mean a function but a bunch of operations.

I am interesting in this because JSHint points out variables as already predefined despite the fact that they have the same name but appear in different functions for example.

UPDATE: I may have been incorrect when asking this so to clear out the situation I have changed the functions.

UPDATE 2 I understand scope. I mean is there any other advantages of one over the other despite the scope?

Upvotes: 2

Views: 163

Answers (3)

Diode
Diode

Reputation: 25155

As others have suggested you must read more about variable hoisting in Javascript. I will try to demonstrate it.

function test() {

    var t1 = msg + " hello";  
    console.log(t1); // prints "undefined hello" because msg is undefined
    var t2 = msgx + " hello"; // msgx ReferenceError

    var a = 1;
    var b = 2;
    if (a > b) {
        var msg = 'sample';
    }

}

test();

Here in the example you can see that msg is declared. but it is undefined. On the other hand msgx causes reference error. It is not declared anywhere. So the point is the statement var msg = 'sample'; which comes later in the function inside if braces makes msg a valid variable everywhere in the function. So again declaring msg will give you predefined variable warning.

In javascript only a function can create a scope. Everything declared in a function will be available in the whole function scope even though there are inner braces of other control statements. All the variables declared in different lines inside a function will be hoisted and treated as if declared in the starting line of the function.

Upvotes: 1

Bill
Bill

Reputation: 3517

Do you understand scope?

In situation B, your variables are only available within the scope of the function.

function(){
    var foo = 10;
}
console.log(foo); //undefined

In situation A your variables are available globally.

var foo;
function(){
    foo = 10;
}
console.log(foo); //10

In situation A, modifying foo from within the function modifies it everywhere. In situation B, only the local variable is modified.

Upvotes: 0

Scientist42
Scientist42

Reputation: 77

Here is nearly no difference ... in each case the variable is defined but in case you won't use msg variable first case would be little bit data-saving :) But this is too simple task.

Upvotes: 0

Related Questions