When ES2016 was introduced, it had two new ways of defining variables called let and const. Earlier, in JavaScript you could only define variables using var.
Var
var is function-scoped or globally scoped. var which is declared outside of the function-scope is available to use by the entire web page. Function-scope means when declared inside the function block, it can not be accessed outside of that function.
var name = "Mike";
/* When we execute this function, it will be able to access variable name.*/
//Output will be "Mike" when this function is executed.
function access_name(){
console.log(name)
}
function my_foo(){
var foo = "hello";
}
console.log(foo); //This will throw an error since variable is inside my_foo function's scope
There is an issue with var declaration. If a variable is defined but redefined later on into the code, it will actually overwrite the initial declaration which may not be the intended behavior you want. It is not wrong, but it can come as a surprise!
var name = "Mike";
var is_true = true;
//In this if block, even when variable name is declared, it will redefined the initial variable name as well
if(is_true){
var name = "Jade";
}
console.log(name) //The output will be "Jade"
Let
Let is an improvised version of the var declaration. It is also the preferred way for variable declaration. It fixes the issue which comes with var which we saw in example above. Let is block-scoped. A block is piece of code between {}. As such a variable declared using let can only be used inside that block.
let name = "Mike";
let is_true = true;
if(is_true){
let name = "Joe";
}
console.log(name) //This will still output as "Mike"
Const
const is an abbreviation for constant. const is also block-scoped but it can not be reassigned.
const PI = 3.14;
PI = 2.14; //This will throw an error since reassignment to const can not happen
To note, if the const is an object or array, new items can be added to it because you are still not reassigning the constant.
const car = ["Honda","Hyundai"];
car.push("Toyota"); //This will push Toyota into car array
const person = {
first_name: "Mike",
age : 29
}
person.last_name = "Doe"; //this will add new key pair value to the person object
I hope this post was helpful to you. If you like my post, follow me @twitter/andramazo.