Exercise – Scope
by heenan
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
var x = 5;
function a() {
console.log(x);
}
function b() {
console.log(x + 5);
}
a();
b();
/*
* 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
var x = 0;
function c() {
var y = 3;
console.log(x);
function d() {
console.log(x + y);
}
function e() {
var x = 4;
console.log(x + y);
}
d();
e();
}
c();
/*
* 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 outer(x) {
inner();
function inner() {
console.log(x+1);
}
}
outer(5);
*/
function outer(x) {
return function inner() {
x = x+1;
console.log(x);
}
}
console.group('Bonus');
var inner = outer(5);
inner();
inner();
inner();