2

I'm trying to understand scope in Javscript, and have some problem. Code:

const callback = (arg) => {
  console.log(arg);
};

function mainFunc(z) {
  const cb = z;
  insideFunc();
}

function insideFunc() {
  cb('1');
}


mainFunc(callback);

Why insideFunc cannot find cb variable?

  cb('1');
  ^

ReferenceError: cb is not defined
    at insideFunc (file:///usr/src/app/file.js:42:3)
    at mainFunc (file:///usr/src/app/file.js:38:3)
    at file:///usr/src/app/file.js:46:1
Yuri Molodyko
  • 590
  • 6
  • 20
  • 3
    Because scope is lexical, not dynamic. Functions can only see variables *where they were declared*, not where they were called. – VLAZ Nov 20 '21 at 14:03
  • 1
    You are trying to call `cb` function. which you have never defined. You have `cb` variable in above scope. Which you can pass in function and then you can access. – Anuj Raghuvanshi Nov 20 '21 at 14:06
  • 1
    Here is an example *why* you would want lexical scope over dynamic - imagine that the declarations of `mainFunc` and `insideFunc` are separated by a lot. Maybe 500 lines, maybe they are in different files. Point is, you cannot *see* the source code. With dynamic scope, if somebody decides to refactor `mainFunc` and rename `cb` to `callback` then they have introduced a bug since now `insideFunc` will be calling something that doesn't exist. Dynamic scope makes functions interconnected, instead of abstracting away functionality. – VLAZ Nov 20 '21 at 14:09

0 Answers0