difference between const let and var code example
Example 1: difference between var and let
var is function scoped and let is block scoped. Let's say you have:
function understanding_var() {
if (1 == 1) {
var x = 5;
console.log('the value of x inside the if statement is ' + x);
}
console.log(x);
}
5
function understanding_let() {
if (1 == 1) {
let x = 5;
console.log('the value of x inside the if statement is ' + x);
}
console.log(x);
}
Uncaught ReferenceError: x is not defined
var is defined throughout the entire function, even if it's inside the if
statement, but the scope of let is always within the curly braces, not outside
it, even if the conditional statement is inside the function.
Example 2: var vs let vs const
var:
- hoisted (always declared at top of scope, global if none)
- function scope
let:
- block scope
- not redeclarable
const:
- block scope
- not reassignable
- not redeclarable
Note: Although it may seem like these hold only semantic meaning, using the
appropriate keywords helps the JS engines' compiler to decide on what to optimize.
Example 3: what is the difference between let and const in javascript
The difference is that with const you can only only assign a value to a variable
once, but with let it allows you to reassign after it has been assigned.