Var, let, and const in JavaScript: a cheatsheet.

LET
We use the let keyword to declare variables that can change later so basically during the execution of our program. ‘Let is mutable i.e. variables declared with let can be changed. We can also declare a ‘let’ variable at one place and assign a value later in the same scope or an inner scope.
let age = 0; let name; function nextYear(){ name "Peter'; aget+; console. log(' ${name} is ${age} year old ); } nextYear(); //Peter is 1 year old nextYear(); //Peter is 2 year old nextYear(); //Peter is 3 year old
Const
We use the const keyword to declare variables that are not supposed to change at any point in the future.
So, the value in a const variable cannot be changed.
- Const variable has to be assigned a value the moment it is created.
- Const variable is immutable i.e. it cannot be reassigned.
- Const variable must have an initial value.
const birthYear = 1867; //correct birthYear = 1956; //error const currentYear; //error
Var
‘Var’ declarations are globally scoped or function scoped.
The scope is global when a ‘var variable is declared outside a function.
This means that any variable that is declared with var outside a function block is available
for use in the whole window.
‘var’ is function scoped when it is declared within a function.
This means that it is available and can be accessed only within that function.
var greet = "Good Morning"; function func1(){ var hello = "hello" ; greet "Good Night"; console. log( hello); console.log( greet ); } func1(); / / hello Good Night console. log( hello); //error: hello is not defined console. log( greet); //Good Night
Which one to use?
‘var’ is basically the old way of defining variables, prior to ES6.
Nowadays we prefer ‘const’ and ‘let’ more.
As best practice for writing clean code, it is recommend to use const’ by default and ‘let only
when you are really sure that the variable needs to change at some point in the future.