Exercise – Scope

by Colin Cheevers

JavaScript

/**
 * Exercise:
 *
 * Function Scope
 *
 * Work in the console, or use "console.log()" to output to the console 
 * from the script
 *
 * 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 two functions that share a non-global variable
 *  - Verify this by logging the value of the variable to the console 
 *    from within each function
 */

//Part 1
var a = 5;

fun1();
fun2();
function fun1() {
	console.log("fun1 : " + a);
    return a;
}
function fun2() {
	console.log("fun2 : " + a);
    return a;
}

//Part 2
function fun3() {
    var myVar = 7;	
    
	function fun4() {
        myVar = 8;
		console.log("fun4 : " + myVar);
        return myVar;
	}
    console.log(fun4());
    return myVar;
}

console.log(fun3());