1

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?

MFave
  • 1,044
  • 2
  • 8
  • 19
  • See also https://stackoverflow.com/questions/44146107/inject-variables-into-function-scope – le_m Jun 01 '17 at 01:26
  • Yes, the reason is lexical scope. Which has nothing to do with first-class functions. – Bergi Jun 01 '17 at 01:48

1 Answers1

0

First, a slight problem with the test: you didn’t pass the function drSideEffect into main; you called it, then passed its return value (nothing). firstClassFunction is undefined, and firstClassFunction on a line by itself is a no-op. Instead, call it in main:

firstClassFunction();

and pass the function without calling it:

main(drSideEffect);

The result will be the same, though, because you’re right: functions inherit the scope where they’re defined and not where they’re called.

Ry-
  • 218,210
  • 55
  • 464
  • 476