I'm having trouble with this JavaScript exercise. I'm given a function that defines three different variable/value pairs and within that function are multiple nested IIFEs that change those same values. The goal of the exercise is to change the variable's values to a certain value. So here is the code that I was presented:
var scopeExercise = function() {
var a = 1,
b = 2,
c = 3;
result = "a: " + a + ", b: " + b + ", c: " + c;
(function firstFunction() {
var b = 5,
c = 6;
(function secondFunction() {
var b = 8;
(function thirdFunction() {
var a = 7,
c = 9;
(function fourthFunction() {
var a = 1,
c = 8;
})();
})();
})();
})();
return result;
};
console.log(scopeExercise());
And they want the var a = 1, b = 8, and c = 6. I'm still having trouble understanding the function scope because I've tried commenting out the thirdFunction and fourthFunction so that they don't get called before the outer functions and it still won't change the values of var a, b, and c. Also, I don't understand why the nested functions aren't getting executed since they should be immediately invoked.
try this:
var scopeExercise = function () {
var a = 1, b = 2, c = 3;
(function firstFunction() {
b = 5;
c = 6;
console.log('firstFunction()');
(function secondFunction() {
b = 8;
console.log('secondFunction()');
(function thirdFunction() {
a = 7;
c = 8;
console.log('thirdFunction()');
(function fourthFunction() {
a = 1,
c = 6;
console.log('fourthFunction()');
})();
})();
})();
})();
result = "a: " + a + ", b: " + b + ", c: " + c;
return result;
}
console.log(scopeExercise());
added the prints that you will see that all functions were executed