Exercise – Scope

Class Exercise 4

by iboulder

HTML

<h1>
Class Exercise 4 - SLM
</h1>

JavaScript

/**
 * Exercise:
 *
 * Function Scope
 *
 * Work in the console, or use "console.log()" to output to the console 
 * from the script
 *
 * You could also use console.assert(boolean) to test your functions
 *
 * Part 1: Write two functions that share the same, global variable
 * 	- Verify this by logging the value of the variable to the console 
 *    from within each function
 */
 
 // write solution to part 1 here
  console.log('\nex 1');

function strAdd(myVar) {
 	return myVar + "ball";
 };
 
 function strPre(myVar) {
 	return 'Goto ' + myVar;
 };

var gVar = "Glow";
 console.log('gVar is ' + gVar);
 gVar = strAdd(gVar);
 console.log('gVar is ' + gVar);
 gVar = strPre(gVar);
 console.log('gVar is ' + gVar);
 
 
 /*
 * Part 2: Write two functions that share a non-global variable
 *  - Verify this by logging the value of the variable to the console 
 *    from within each function
 *
 *    Hint: You can write functions inside of other functions...
 */
 
 // write solution to part 2 here
 
 console.log('\nex 2');
 console.log  ('starting gVar is ' + gVar)
 console.log(outer(gVar));
 console.log(outer(gVar));
 
 function outer(myVar) {
 	myVar += " Variable";
  console.log('outer myVar is ' + myVar)
  
 	function inner(myVar){
    myVar += " Temp";
    console.log('inner myVar is ' + myVar)  
  }; // inner
 
 }; //outer
 
 
  /*
 * Bonus: Write a function (outer) that returns another function (inner)
 *
 * The outer function expects one Number parameter, x
 * The inner function should add 1 to x and log it to the console
 * 
 * Hint: You will need to run the outer function once
 * in order to get the inner function
 */
 
 // write solution to bonus here
 function secrectMker(x) {} //see slides