I've run into a particularly interesting case of what I believe to be a side-effect in Javascript.
I'm trying to wrap my head around scope and the fact that functions are first-class citizens. Please let me know if I'm on the right track, and forgive me if this is somewhat of a novice question.
Make reference to the following code:
let mrGlobal = "mrGlobal";
let drSideEffect = function() {
mrGlobal = "mrGlobal has been acting weird lately";
}
function main(firstClassFunction) {
let mrGlobal = "mrGlobal: version 2.";
firstClassFunction
console.log(mrGlobal) //First console.log
}
main(drSideEffect());
console.log(mrGlobal) //Second console.log
In the case of the first consol.log the output is: mrGlobal version 2.
In the case of the second consol.log the output is: mrGlobal has been acting weird lately
I initially thought that this would result in the opppsite behaviour (First console.log switched with second console.log) so this output surprised me. I'm assuming this is because functions in javascript are bound to the scope in which they are declared and not to a scope that executes them - even if they are passed into that scope as first-class citizens?