- Use REPL
- Access global
- Use explicit vs. implicit declarations
Scoping is about defining and accessing variables/objects/functions. Here's a small example which can illustrate how dangerous it can be to not understand scope: our program uses a variable named list
and module A uses a variable named list
. When we import module A, the original list
of the program is lost!
Understanding global and scoping will give you a good foundation for future development.
In this lab, we're going to be using the Node REPL to create several bank accounts and users in different scopes.
- Enter Node REPL
- Print the
global
object - Print the
process
object (global.process
) - Create a global variable
user
explicitly withglobal.user = {admin: false}
- Create a global variable implicitly with
var account = {balance: 1000}
- Open a new REPL and check for values of user and account (ReferenceError means the variable is undefined)
- Go back to the first REPL and print user and account with
global.user
andglobal.account
- Delete
user
withdelete user
(true) and print it again. You should getReferenceError
because you deleteduser
. - Delete
account
withdelete account
(false) and print it again ({balance: 1000}) - Exit REPL
- Contemplate on the fact that user and account reacted differently to the
delete
operator. Read the extra info if you forgot howdelete
works (it's JavaScript and not exclusive to Node).
To understand the discrepancy, you need to know how delete
works and what was the difference between user
and account
in the ways they were created (explicit with global
vs. implicit with var
).
View node-global-lab on Learn.co and start learning to code for free.
View Node Global Lab on Learn.co and start learning to code for free.