Var
A small article showing the differences between these variable calls.
Var/Let/Const: What are the differences
What is Var?
Essentially these limit the scope of the variables that we set in JS. If we simply write out a variable without declaring var
, we are defining a global variable by default. If we structure JS code so that we wrap everything within a constructor function, we can use var to declare an instance variable.
Var hoisting
Hoisting is a mechanism of Javascript. Variable and function declarations are moved to the top of the scope before code execution. If we do this:
console.log(greeter);
var greeter = "Hello world"
Javascript will interpret it like this:
var greeter;
console.log(greeter); //greeter is undefined
greeter = "Hello world"
It is good that we have been taught to define the instance variables right at the top of a class in Ruby, so that we can prevent any undesired hoisting:
var greeter = "Hello world"
console.log(greeter);
What is the problem with var?
Here's an example:
var greeter = "Say hi";
var times = 4;
if(times > 3){
var greeter = "Hello world";
}
console.log(greeter); //"Hello world"
While the above works as intended, it can become a problem when we forget that we've already defined greeter
in a large file with loads of code. The redefinition will always happen and this can probably break a load of code if we do it accidentally.