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.login this exercise). -
Invoke the function
printGafter you have set value forg. (invoke the function means "call the function, execute it"). -
Invoke the function
printGone more time. But this time put the invocation (function call) on the first line ofapp.jsfile. - Take a moment to think - why do you get the results you get? Hint: remember hoisting and execution!
-
Create two functions:
aandb. Leave their body empty for now. - Invoke function
afrom the global context. - Invoke function
bfrom the global context. -
Create variable
x=12- it must be available in both functionsaandbas well as the global context. To test if it works: print the value ofxin functiona, functionband globally. -
Print
window.xin 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 functionaand nowhere else. Test if it works correctly: printing it should work from functiona, but should fail from functionband also from the global context. -
Create a new function
cand have a variablez=667in such a way thatzis available inside functionsbandc, but nowhere else. Hints:- Think about outer environments!
- Where should you place function
c?
Solution
You can find a solution here.