Defending variables in JS have its own way.
We have three ways to defend a variable let
, var
, const
.
Var | Let | Const | |
---|---|---|---|
Changeable | ✔ | ✔ | |
Block Scope | ✔ | ✔ | |
Global Scope | ✔ | ||
Make Arrays | ✔ | ✔ | ✔ |
We mostly use
let
because of the block scope which I'll explain in the below. 👇🏻
Let
The keyword let
makes a variable only useable within the scope it made in, you can't use it outside that scope.
E.g.
{ | |
let num = 10; | |
console.log(num); // Outputs: 10 | |
} | |
console.log(num); // ERROR |
Var
The keyword var
makes a global variable, you can use it everywhere in the code.
E.g.
{ | |
var num = 10; | |
console.log(num); // Outputs: 10 | |
} | |
console.log(num); // Outputs: 10 |
Const
The keyword const
makes an unchangeable variable, you can't change its value.
E.g.
const pi = 3.14159265359; | |
pi = 4; // ERROR |
Top comments (1)
Thaks for sharing that with me, sorry for the mistake. 🙏🏻
I've heard that the block scope is taking less memory space then the general. Thanks for clearifying. 👍🏻👍🏻