Difference between var and let and const code example
Example 1: let vs const
`const` is a signal that the identifier won't be reassigned.
`let` is a signal that the variable may be reassigned, such as a counter in a
loop, or a value swap in an algorithm.
It also signals that the variable will be used only in the block it's defined
in, which is not always the entire containing function.
Example 2: 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);
}
//output: the value of x inside the if statement is 5
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);
}
//output: the value of x inside the if statement is 5
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 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.
Example 4: difference between var let and const in javascript with example
//functional scope
var a; // declaration
a=10; // initialization;
//global scope
// re-initialization possible
let a;//only blocked scope & re-initialization possible
a=10;
let a =20;
if(true){
let b =30;
}
console.log(b); // b is not defined
const // const also blocked scope,Re-initialization and re-declaration not possible
const a; // throws error {when we declaring the value we should assign the value.
const a =20;
if(true){
const b =30;
}
console.log(b); // b is not defined
console.log(a); // no output here because code execution break at leve b.