Read a variable declared outside the function from inside it.
Acceptance criteria
- 1.#out should show My Site.
JavaScript Tutorial · JavaScript Scope & Hoisting
These 10 tasks go with the JavaScript Scope chapter. 5 of them ask you to build something small from scratch; 5 give you code that is already broken and ask you to work out why. Set aside about 90 minutes for the whole set, though you can do them in any order.
Nothing here is marked by a person. When you press Submit, the editor checks your code against the points listed under each task and tells you straight away what passed and what didn't (you need a free account to submit). If you get stuck, there are hints, and a worked solution once you've had a go. The first 2 tasks are free; the rest are part of the practice plan.
If it's been a while since you read the chapter, here is how it starts: “JavaScript scope decides where in your code a variable can be seen and used.” .
1.Read a global variableexercise · easy · 10 min
Read a variable declared outside the function from inside it.
Passes when: #out should show My Site.
2.Keep a variable localexercise · easy · 10 min · practice plan
Show that a variable declared inside a function does not exist outside.
Passes when: #out should show undefined.
3.Walk the scope chainexercise · easy · 10 min · practice plan
Join a value from each of three nested scopes with a dash.
Passes when: #out should show one-two-three.
4.Shadow an outer variableexercise · easy · 10 min · practice plan
Declare a variable inside a function with the same name and show the outer one is untouched.
Passes when: #out should show outer.
5.Pass instead of sharingexercise · medium · 10 min · practice plan
Pass a value into a function rather than reading a global, and show the result.
Passes when: #out should show 60.
6.Fix the variable read out of scopebug fix · easy · 8 min
The variable only exists inside the function.
Passes when: #out should show 42.
7.Fix the shadowed valuebug fix · easy · 8 min · practice plan
The inner variable hides the outer one, so the wrong value is returned.
Passes when: #out should show outer.
8.Fix the broken scope chainbug fix · easy · 8 min · practice plan
The inner function cannot see a variable declared after it runs.
Passes when: #out should show one-two-three.
9.Fix the hidden global dependencybug fix · easy · 8 min · practice plan
The function reads an outside rate, so changing it changes the answer.
Passes when: #out should show 60.
10.Fix the outer variable overwrittenbug fix · easy · 8 min · practice plan
The function changes the global instead of using its own copy.
Passes when: #out should show start.
Between them these tasks cover Global scope, Function scope and Scope chain.
Looking for a different chapter? See every practice set, or switch to the interview theory questions.