Exercise 12.1
This is Exercise 12.1, lecture on Javascript quirks, used in the course IDATA2301 Web technologies at NTNU, campus Aalesund.
Purpose
The purpose of the exercise is practice understanding variable scope and creating variables in the scope you want them to be.
Instructions
-
Create a new HTML document. Include a file named
app.js
. In this exercise you will be placing all the Javascript code inapp.js
. -
Create a global variable named
g
, set valueg=3
. -
Create a function
printG
. Inside it print a message"The value of g is " + g
(by print we meanconsole.log
in this exercise). -
Invoke the function
printG
after you have set value forg
. (invoke the function means "call the function, execute it"). -
Invoke the function
printG
one more time. But this time put the invocation (function call) on the first line ofapp.js
file. - Take a moment to think - why do you get the results you get? Hint: remember hoisting and execution!
-
Create two functions:
a
andb
. Leave their body empty for now. - Invoke function
a
from the global context. - Invoke function
b
from the global context. -
Create variable
x=12
- it must be available in both functionsa
andb
as well as the global context. To test if it works: print the value ofx
in functiona
, functionb
and globally. -
Print
window.x
in the console. Did you see12
? -
Create a variable
y=15
. Choose the right place (lexical environment) for the variable: it should be available only inside functiona
and nowhere else. Test if it works correctly: printing it should work from functiona
, but should fail from functionb
and also from the global context. -
Create a new function
c
and have a variablez=667
in such a way thatz
is available inside functionsb
andc
, but nowhere else. Hints:- Think about outer environments!
- Where should you place function
c
?
Solution
You can find a solution here.