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?;


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


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) { = name;
  this.favouriteFood = favouriteFood;
  this.hello = function() {
    var result = "Hello, my name is " + + " and I like to eat: ";
    for(var i = 0; i < favouriteFood.length - 1; i++) {
      result += favouriteFood[i] + ', ';
    result += favouriteFood[i];

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

for(var i = 0; i < contacts.length; i++) {

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.


Thanks for your help ^^


You're very welcome :slight_smile:


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