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?
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));
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));