New Variables — Creation, Updating and Scoping Flashcards
What is the most important new feature of Let and Const variables?
They are Block Scoped.
var is function scoped.
Can var variables be updated?
Yes
Can var variables be redefined?
Yes
Name the most important benefit of using let and consts and explain why it is important.
Rather than being scoped to the function, it is scoped to the block.
This prevents variables leaking out of blocks into parent functions and even the window in certain cases.
How do you spot a block statement?
Name an example.
An opening and closing bracket is a block statement.
e.g an if statement
if {
}
Can you update a variable
Yes
Can you redefine a redefine a variable in the same scope
Yes
Can you redefine a let in the same scope
No, it will throw an error
Why is it useful that let and const don’t allow you to redefine them?
Prevents duplicates through accidents that can cause bugs.
Can const variables be updated?
No. But with objects properties my be updated.
Can let variables be updated?
Yes
In a script tag you write:
let result = true inside an if statement;
what would you get if you logged result in the browser and why?
Nothing because the let variable is block scoped locally inside an if statement.
In a script tag you write:
let result = true
what would you get if you logged result in the browser and why?
You would get ‘true’.
Because the let var is block scoped it would be attached to the window and can therefore be found by a console.log
Can you reassign a const variable object.
Name an example that illustrates this relationship.
You can’t reassign them. The same object will always be used and cannot be wiped.
Properties updatable.
Just like a person you wouldn’t change their name or body, but their age be changed.
Two reasons for using let and const
Scope something to a block
Creating a variable that cannot be changed