- Redefining :
Const ==> Constant : Cannot be reassign. Example :
const name='Romain';
name='Thomas'
console.log(name) ==> Error
Const cannot be reassigned but can be manipulated Let, var : Can be reassign Example :
let name='Romain'
name='Thomas'
- Function Scope :
function myFn() {
var foo = 'peekaboo!';
console.log(foo); // 'peekaboo!'
}
console.log(foo); // ReferenceError: foo is not defined
- Block Scope :
if (true) {
var foo = 'peekaboo!';
let bar = 'i see u';
const baz = 'baby blue!';
console.log(foo); // 'peekaboo!';
console.log(bar); // 'i see u';
console.log(baz); // 'baby blue!';
}
console.log(foo); // 'peekaboo!';
console.log(bar); // ReferenceError: bar is not defined
console.log(baz); // ReferenceError: baz is not defined
- For loop scope :
for (var i = 0; i < 3; i++) {
console.log(i);
}
console.log(i);
Var is accessible outside of for loop, confitionnal Block but not accessible outside of a function. Let, Const are not accessible outside loop, conditionnal blocks and function.
Avoid var because function-scope Source : https://alligator.io/js/var-let-const/