+ 1

Scope in JavaScript

How can we access x,y in innermost function in the following code. We are returning from function a. Then how can we access x inside functions b,c? https://code.sololearn.com/WHgCZ4t6I9a8/?ref=app

15th Nov 2018, 12:35 PM
Sindhe Kishan
Sindhe Kishan - avatar
5 Respostas
+ 4
Usually after a function is called and returned that function's scope should be closed. But as the inner function still accesses the outer functions parameter it's still open and not closed. Maintaining a sort of closure. Read the mdn docs from "function scope" heading till "closures" https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Functions
16th Nov 2018, 4:17 AM
Lord Krishna
Lord Krishna - avatar
+ 2
x & y is already available in the innermost functions replace 1 with 10 to see the result. You are even using the values correctly.
15th Nov 2018, 12:51 PM
Lord Krishna
Lord Krishna - avatar
+ 1
1. An inner function has access to the scope of his outer function. (you can think of ...inherits the outer scope) 2. A parameter definition is an indirect variable declaration. (function (a) {} got an variable named a in its scope. The value of the variable is defined at invocation time and will be the first value passed to the function call)
15th Nov 2018, 7:20 PM
Andreas
Andreas - avatar
0
Please check the JS part in the code
15th Nov 2018, 12:36 PM
Sindhe Kishan
Sindhe Kishan - avatar
0
In line 2 we are returning from function a, then how are we able to access x inside b. Isnt scope of function a expires once we return from it. ? please explain
15th Nov 2018, 2:23 PM
Sindhe Kishan
Sindhe Kishan - avatar