Difference Between Let and Var and Const in JavaScript
First What are these terms, let, var and const? Let’s learn. These terms are used in JavaScript. These 3 terms function like variables actually. However, these terms have their own specialties which we will study in-depth in this article
Var in JavaScript
In 2015, an update to JavaScript was introduced to bring the term called let. However, before that var was used commonly. Var actually means variable.
Var is used as a globally scoped variable when it needs to be declared outside of a function and is scoped when it’s declared in a function.
Here’s an example:
var test = "Welcome!"; function myFunction() { var world = "world"; }
var test = "Welcome"; function myFunction() { var world = "world"; } console.log(hello); // error: variable world is not defined
We’ll get an error because the variable world is outside of the function.
Let in JavaScript
Let came in the 2015 ES6 JavaScript update. Let is preferred for variable declaration. Let is also better than var. Let’s learn about let.
Let is block scoped. This means let is only allowed to use within one block. A block is known as a piece of code in the curly bracket symbol { }.
For example:
let test = "Welcome"; let times = 4; if (times > 3) { let world = "World"; console.log(hello);// "say World instead" } console.log(hello) // Error: World is not defined
In this case, since the world is outside its block, it returns an error. This is because let variables are block scoped as mentioned earlier.
50+ HTML, CSS & JavaScript Projects With Source Code
Const in JavaScript
Const exists for quite some time too. Const actually stands for constant. Const shares some similarities with let anyhow. Const declarations are also block-scoped like let. However, let can be updated but const can’t be updated too.
For example, in let we can do:
let test = "Welcome"; test = "World";
However, the behavior is different when objects are declared with const. A const object can’t be updated but the const object properties can be updated like below:
const test = { message: "Welcome", times: 4 }
And that’s all the differences between let, var, and const!
Thanks for reading! Do contact me via the comments and methods below if you have to say anything:
written by @codingporium