1

In JavaScript The output of the below code snippet is [2,1,2]

function func(x, f = () => x) {
    var y = x;
    x = 2;
    return [x, y, f()];
};
console.log(func(1));

In JavaScript output of below code snippet is [2,1,1]

function func(x, f = () => x) {
    var x;
    var y = x;
    x = 2;
    return [x, y, f()];
};
console.log(func(1));

I was expecting both the code snippets to have same output. But it is not the case.

  • The first version modifies the parameter `x`, the second has a variable `x` that *shadows* the parameter `x`. Since the function `f` returns the *parameter* `x` and not the function-scoped *variable* `x`, you get `1` instead of `2` because parameter `x` is never modified in the second version the way it is in the first. – Jared Smith Nov 17 '22 at 15:39
  • If the variable x is shadowing the parameter x then how can variable y get the value of parameter x ? variable y should be undefined right ? – Smruti Pattanaik Nov 19 '22 at 01:09
  • No because you didn't assign it yet the runtime will resolve it to the parameter x. Assigning any value (even an explicit set of `var x = undefined` will cause the shadowing. – Jared Smith Nov 19 '22 at 02:22

0 Answers0