0

I was reading and coding along with this tutorial from javascript.info. I can't understand why in these two examples the outcomes are different.

Here the userName variable changes from "John" to "Bob":

let userName = 'John';

function showMessage() {
  userName = "Bob"; // (1) changed the outer variable

  let message = 'Hello, ' + userName;
  alert(message);
}

alert(userName); // John before the function call

showMessage();

alert(userName); // Bob, the value was modified by the function

And here it stays "Ann":

function showMessage(from, text) {

  from = '*' + from + '*'; // make "from" look nicer

  alert(from + ': ' + text);
}

let from = "Ann";

showMessage(from, "Hello"); // *Ann*: Hello

// the value of "from" is the same, the function modified a local copy
alert(from); // Ann

Can someone help me understand why this happens?

VLAZ
  • 22,934
  • 9
  • 44
  • 60
CyberM
  • 9
  • 1
    In the first, the closest (lexical) declaration of the variable is the top level, so that outer variable is changed. In the second, the closest declaration is in the same block (the argument), so the argument is changed, and not the outer variable. – CertainPerformance May 09 '22 at 17:22

0 Answers0