Scope allows programmers to control the flow of information through the variables in their program. Some variables you want to set as constants (like pi), which can be accessed globally. Others you want to keep secure to minimize the danger of accidental updates. For example, a variable holding someone's username should be kept secure.
Variable shadowing is where two variables in different scopes have the same name. The variables can then be accessed under different contexts. However, shadowing can affect the variable's accessibility. It also causes confusion for anyone reviewing the code.
Example
1const input = require('readline-sync');
2
3function hello(name) {
4 console.log('Hello,', name);
5 name = 'Ruth';
6 return doubleName(name);
7}
8
9function doubleName(name){
10 console.log(name+name);
11 return name+name;
12}
13
14let name = input.question("Please enter your name: ");
15
16hello(name);
17doubleName(name);
18console.log(name);
So, what is the value of name
in line 4, 10, 16, 17, and 18?
Yikes! This is why shadowing is NOT a best practice in coding. Whenever possible, use different global and local variable names.
Try It!
If you are curious about the name
values in the example, feel free to
run the code here.
Variable hoisting is a behavior in JavaScript where variable declarations
are raised to the top of the current scope. This results in a program being able
to use a variable before it has been declared. Hoisting occurs when the var
keyword is used in the declaration, but it does NOT occur when let
and
const
are used in the declaration.
Note
Although we don't use the var
keyword in this book, you will see it a
lot in other JavaScript resources. Variable hoisting is an important concept
to keep in mind as you work with JavaScript.
Question
What keyword allows a variable to be hoisted?
let
var
const
Question
Consider this code:
1let a = 0;
2
3function myFunction() {
4 let a = 10;
5 return a;
6}
Because there are two separate variables with the name, a
, under the two different scopes, a
is being shadowed.