I was learning about arrow function in js where I found one question
console.log((function(x, f = () => x) {
var x;
var y = x;
x = 2;
return [x, y, f()];
})(1));
It's output is 2,1,1 but it should be 1,1,1.
Can anyone explain it?
Here is the function re-written to show what is happening.
main takes x = 1defaultFunction returns the original x = 1resultFn is a function that gets called inside of main that takes xy is assigned the x that was passed all the way down (local -scope) 1x is reassigned to 22, 1, 1This is an exercise on variable/parameter scope.
const main = (x) => { // x = 1
const defaultFn = () => x; // x = 1
const resultFn = (x, f = defaultFn) => { // x = 1
var x; // x is still 1
var y = x; // y = 1
x = 2; // x = 2
return [x, y, f()]; // x = 2, y = 1, f() -> 1
};
return resultFn(x); // 2, 1, 1
};
console.log(main(1));
var x; to introduce a new, uninitialized variable that shadows the parameter x. I was surprised that y was set to 1 and not undefined. With this question and your answer I learned that var x; is a redeclaration and let x; causes an error.You set x to 2 thus it got returned as 2. Change x to 1. Fixed Code:
console.log((function(x, f = () => x) {
var x;
var y = x;
x = 2;
return [x, y, f()];
})(1));
x = 2;1? Or what this even has to do with arrow functions at all, since the only difference in the result isn't produced by an arrow function? If the only difference you're seeing from observed vs. expected results is the first value in the response, simplify the code and refactor out anything unrelated to that first value. What do you end up with?console.log([2, 1, 1])prints2, 1, 1instead of1, 1, 1?