JavaScript Variable Declaration and Scope Flashcards
Learn about the different ways to declare variables and scope in JavaScript
What are the three ways to declare variables in JavaScript?
The three ways to declare variables are:
- var
- let
- const
What does var do?
Var declares a variable, optionally initialising it to a value.
What does let do?
Let declares a block scoped variable, optionally initialising it to a value.
What does const do?
Const declares a block-scoped, read-only name constant.
What are the scopes that variables can belong to?
The scopes that variables can belong to are:
- Global scope
- Module scope
- Function scope
What additional scope can variables declared with let or const belong to?
Variables declared with let or const can belong to the block scope.
What is global scope?
Global scope is the default scope for all code running in script mode.
What is module scope?
Module scope is the scope for running code in module mode.
What is function scope?
Function scope is the scope created with a function.
What is block scope?
Block scope is the scope created with a pair of curly brackets.
Where can global variables be accessed?
Global variables can be accessed anywhere in the document.
Where can local variables be accessed?
Local variables can be accessed inside the function they were defined.
What does variable hoisting mean?
Variable hoisting means that you can refer to the variable anywhere in its scope, even if its declaration isn’t reached yet.
What declaration type do you need to use for variable hoisting?
You need to use var if you want to do variable hoisting.
What happens if you access a hoisted variable before it is declared?
If you access a hoisted variable before it is declared its value will be undefined because only its declaration and default initialisation will be hoisted.
Where should all var statements be placed in a function?
As close as possible to the top.
How is hoisting var declarations different from hoisting function declarations?
Var declarations only host the declaration but not the value, function declarations are hosted entirely.
Can you change a constants value through assignment?
No.
Can you re-declare a constant while the script is running?
No.
Does const prevent mutations?
No you are able to mutate constants.