difference between let and var and const in javascript code example
Example 1: Difference between let and var in javascript
let a = 'hello';
var b = 'world';
console.log(window.a);
console.log(window.b);
var a = 'hello';
var a = 'world';
let b = 'hello';
let b = 'world';
Example 2: var let const javascript
Const vs Let vs Var
const pi = 3.14
pi = 1
cannot do this becuase with const you cannot change the value
_____________________________________
Let --> is block level
for(let i = 0; i < 3; i++) {
console.log(i) --> it will console here
}
console.log(i) ---> Not here
---------------------------------------
Var is for variables available to the entire function
for(var j = 0; j < 3; j++) {
console.log(j) --> it will console here
}
console.log(j) ---> it will console here
Example 3: const let var scope
var num = 1;
const num = 2;
let num = 3;
Example 4: 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 5: 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 6: difference between var let and const in javascript with example
var a;
a=10;
let a;
a=10;
let a =20;
if(true){
let b =30;
}
console.log(b);
const
const a;
const a =20;
if(true){
const b =30;
}
console.log(b);
console.log(a);