Can a function be executed within the variable scope of another function?

23 hours ago 3
ARTICLE AD BOX

No. JavaScript uses static scope, not dynamic scope.
That means a function resolves variables from where it was defined, not from where it is called.

In short, a function cannot automatically execute inside another function's local scope.


This works because g explicitly passes x and y:

function g(m = null) { let x = 5, y = 3, z = 11; if (m) return m(x, y); } console.log(g(function (a, b) { return a * b; })); // 15

This does not work because x and y are not in the callback's static scope:

function f(m = null) { let x = 5, y = 3, z = 11; if (m) return m(); } console.log(f(function () { return x * y; }));

See Lexical Scope in JavaScript – What Exactly Is Scope in JS?


If you want to correct this:

function f(m = null) { let x = 5, y = 3, z = 11; if (m) return m(); } console.log(f(function () { return x * y; }));

change to:

function f(m = null) { let x = 5, y = 3, z = 11; if (m) return m({ x, y, z }); } console.log(f(function ({ x, y }) { return x * y;})); // 15 console.log(f(function ({ x, z }) { return x + z;})); // 16

Working Preview

preview

Read Entire Article