# How it works this code?

var q = (function(x,foo = () => x) {
var x;
var y = x;
x =3;

return [x,y,foo()];
})(2)
console.log(q) // [3,2,2]

why is foo() returns 2 and not 3 ?
March 23rd 20 at 19:45
March 23rd 20 at 19:47
To understand what is happening, you just need to look. For example:
Example
``````var q = (function(x,foo = () => x) {
console.log('a)',x,y,foo()); //2 undefined 2
var x;
console.log('b)',x,y,foo()); //2 undefined 2
var y = x;
console.log('c)',x,y,foo ()); //2 2 2
x =3;
console.log('d)',x,y,foo ()); //3 2 2
return [x,y,foo()];
})(2)
console.log(q) // [3,2,2]``````
A more detailed example
``````var q = (console.log('init q',typeof x) //q init to undefined
function(x,foo = (console.log('init foo',x),() => x)) { //init foo 2
console.log('a)',x,y,foo()); //2 undefined 2
var x;
console.log('b)',x,y,foo()); //2 undefined 2
var y = x;
console.log('c)',x,y,foo ()); //2 2 2
x =3;
console.log('d)',x,y,foo ()); //3 2 2
return [x,y,foo()];
}
)(2)
console.log(q) // [3,2,2]``````

In General, there are at the time of initialization of the foo function is visible to the scope the anonymous function. But these local scopes have anonymous functions like two really. The first one contains the parameters of the function, and the second - the local variables of a function. And this var x is sitting in the second and overlaps the first field of view. That is, foo doesn't see the var x and only sees the one x, which is in the settings, because foo itself is also sitting in the first scope. I hope is available.
March 23rd 20 at 19:49
It's all in the Declaration of variables.
var declares a variable X within the function scope, at the time, as a function accesses the X inside the block scope braces {}.

let-const-var;
scope;
var declares the variable as a global
lol into? this is where you subtracted? - Barbara_Schowalter7 commented on March 23rd 20 at 19:52
@Barbara_Schowalter7, I agree, so correctly expressed his thought that got stupid.
Of course, we are talking about what var x is a variable inside of all functions (globally relative to the braces), and let x inside the field braces (local to the braces).
Corrected. - kennith.Wiega commented on March 23rd 20 at 19:55
@Brady.Wiega, so it is true, but there are actually all cheese-pine forest because of the circuit and not due to the way variable declarations - Barbara_Schowalter7 commented on March 23rd 20 at 19:58

Find more questions by tags JavaScript