So i just discovered that var keyword is not necessarily needed when making a global variable but is it best If I do put? If so why? Else why?;


#1

Did you see what did there with the tittle :wink:


#2

Omitting var does not create a global variable. The interpreter will try to find this variable in the nearest scope and will overwrite it, only if it is not found global variable will be created.

var is more readable. When you use var it's clear that you are declaring a new variable. When I don't see a var I usually suspect that programmer wanted to change value of already defined variable.

It does not make sense to pollute the global namespace. In big projects, you would have to keep a list of all the names you have already used to not overwrite important value.


Take a look at this code:

var Person = function(name, favouriteFood) {
  this.name = name;
  this.favouriteFood = favouriteFood;
  this.hello = function() {
    var result = "Hello, my name is " + this.name + " and I like to eat: ";
    for(var i = 0; i < favouriteFood.length - 1; i++) {
      result += favouriteFood[i] + ', ';
    }
    result += favouriteFood[i];
    console.log(result);
  };
};

var contacts = [new Person("Jonh", ["pizza", "chocolate", "french fries"]), new Person("Mary", ["bacon", "ice cream", "burgers"])];

for(var i = 0; i < contacts.length; i++) {
  contacts[i].hello();
}

It returns:

Hello, my name is Jonh and I like to eat: pizza, chocolate, french fries
Hello, my name is Mary and I like to eat: bacon, ice cream, burgers

But without var in the for loops it would result in this output:

Hello, my name is Jonh and I like to eat: pizza, chocolate, french fries

Why? Because value of i was changed during the function execution.

This code is short and trivial, but imagine having a lot more functions with nested calls. It would be a nightmare to keep track of all the variable names you use.


Use var, always. Or let and const in ES6.


#3

Thanks for your help ^^


#4

You're very welcome :slight_smile:


#5

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.