0

var x = 5;

function test2(x) {
  x = 7;
}

test2(8);
alert(x);

Why exactly is this putting out the global var x=5, without being affected by anything within the function.

evolutionxbox
  • 3,932
  • 6
  • 34
  • 51
sevien
  • 1
  • 1
    The `x` parameter in the function is [shadowing](https://medium.com/@mayuminishimoto/understanding-variable-shadowing-with-javascript-58fc108c8f03) the variable from the outer scope. – JLRishe Jan 22 '21 at 14:59
  • Try changing `test2(x)` to `test2(a)`. – evolutionxbox Jan 22 '21 at 14:59
  • @Justinas that's not the correct dupe target. We have one for specifically this scenario when a parameter shadows a variable somewhere. It's nothing to do with references. – VLAZ Jan 22 '21 at 15:01

1 Answers1

0

Because you passed a param called x, which is the same name as your global var. Try this out:

var x = 5;

function test2(y) {
  x = y;
}

test2(8);
alert(x);
silencedogood
  • 3,209
  • 1
  • 11
  • 36