Differences between var let and const in javascript

Differences between var let and const in javascript

What are those var let and const keywords in javascript?

Well, they are use to define variables. Lets take every one of them and discuss more:

1. Var

This keyword was used from the beginnings of javascript, but it had some weird behaviour.

Example:

for(var i = 0; i< 3; i++){
  console.log(i);
}

console.log(i);

What do you think about the code above?

If you are coming from other languages you’ll say that it will output: 0, 1, 2 and then it will throw and error because we tried to print our i variable after the execution of the for statement. right? Javascript might surprise you and will not throw any error and the variable have the value 3.

Why?

The answer is that in javascript when you declare a variable using the keyword var, that variable will live inside the function scope and not on the block scope as it is in other programming languages.

2. let

As of ES2015(ES6) a lot of other features were delivered to javascript. Two of them were let and const which came to fix the problems that we had before using var.

Variables declare with let now have block scope, so they live inside the block that were defined.

3. const

The keyword that javascript was missing is const. This const keyword is used to define variables that act as constants, meaning that ones they are assigned a value it’s guaranteed that it won’t change, so at the moment that you declare them you also have to supply a value.

Example:

const value10 = 10; //assign the constant value 10
value10 = 11; // will result in an error because value10 is a constant variable

const value20; //will result in an error because it's forbidden to declare a const variable without an initializer

const objectConstant = {};
objectConstant.x = 10; //will not throw any errors because we are not trying to change our reference variable, but instead we are just mutating our object
objectConstant = {}; //will result in an error as we are changing the reference to which objectConstant was pointing to

I hope that now you understand what are these three keywords in javascript.

Related Posts