var declarations are globally scoped or function scoped while let and const are block scoped. var variables can be updated and re-declared within its scope; let variables can be updated but not re-declared; const variables can neither be updated nor re-declared.
A var variable can be redeclared and updated.
A let variable be be updated but not redeclared.
The Scope of let
If I declare a let variable at the global scope, then redeclare it within a block (curly brackets) as in the example below, I will not get an error in the console, but it will not actually redeclare let.
let points = 50;
let winner = false;
if(points > 40) {
let winner = true;
}
// If I call:
winner
// It returns the first value:
false
Why is this happening?
Because let winner = false and let winner = true, are actually two separate variables because they are scoped differently, even though they have the same name. To clarify:
// This 'let' is scoped to the window (globally):
let winner = false;
if(points > 40) {
// This 'let' is scoped to the block (between the curly brackets):
let winner = true;
}
In the above example if we change bothletvariables to var, then call winner in the console it returns true because it is not inside a function. (Remember: var is function scoped.) The var variable is being redeclared within its scope, which is the window in this case.
let points = 50;
var winner = false;
if(points > 40) {
var winner = true;
}
// If I call:
winner
// It now returns:
true
The Differences Between let and const
const variables cannot be updated. let variables are made to be updated.
// If I define the const variable:
const key = 'xyz123';
// Then try to redeclare it:
key = 'xyz1234'
// I get the following error:
Uncaught TypeError: Assignment to constant variable.
References:
https://www.freecodecamp.org/news/var-let-and-const-whats-the-difference/#:~:text=var%20declarations%20are%20globally%20scoped%20or%20function%20scoped%20while%20let,be%20updated%20nor%20re%2Ddeclared.
No comments:
Post a Comment