The let keyword
Like var, let is used to declare variables. In its simplest form, it's used similarly.
let a;
console.log(a);
console.log(a);
undefined
let a = 5;
console.log(a);
console.log(a);
5
If you declare a variable more than once using let, it'll produce an error.
let a = 5;
let a = 10;
console.log(a);
let a = 10;
console.log(a);
Uncaught SyntaxError: Identifier 'a' has already been declared
Unlike var, if you try to access a variable before it is declared, you'll get an error. Hoisting does not apply.
console.log(a);
let a;
let a;
Uncaught ReferenceError: Cannot access 'a' before initialization
Unlike var, a variable declared in a block using let cannot be accessed outside of that block.
let a = 5;
if (a > 5)
{
let b = a;
}
else
{
let b = a + 1;
}
console.log(b);
if (a > 5)
{
let b = a;
}
else
{
let b = a + 1;
}
console.log(b);
This is the error that will be produced. Variables declared using let are block-scoped.
Uncaught ReferenceError: b is not defined
Again, any variable declared using let cannot be accessed outside of the block it was declared in.
for (let i = 0; i < 5; i++)
{
}
console.log(i);
{
}
console.log(i);
Uncaught ReferenceError: i is not defined
Where functions are concerned, let behaves just like var.
let a = 10;
function x()
{
a = 0;
}
x();
console.log(a);
function x()
{
a = 0;
}
x();
console.log(a);
0
function x()
{
let a = 0;
}
x();
console.log(a);
{
let a = 0;
}
x();
console.log(a);
Uncaught ReferenceError: a is not defined
Now try this...
let a = 10;
function x()
{
let a = 0;
}
x();
console.log(a);
function x()
{
let a = 0;
}
x();
console.log(a);
When you try to access a at the end, you get 10 instead of 0. That's because a is now declared as a variable using let, within function x(), thus the value of that a can't be accessed.
10
What we've learned
let is block-scoped. Thus if a variable is declared inside a block, it cannot be accessed outside of it.Any variable declared using let cannot be redeclared, though its value may be reassigned.
let is stricter than var and is subject to more limitations. This is a good thing in the sense that rectifying (or better yet, avoiding altogether) the resultant reference and syntax errors will in turn help the programmer avoid logic errors down the road.
No comments:
Post a Comment