I'm currently studying JavaScript and I have a question with function parameters. I have this function:
//Function 1
let from = 'Ann';
function showMessage(from, text) {
from = 'Jane';
alert(from + ' says ' + text);
}
showMessage(from, 'Hello');
alert(from);
//Function 2
let userName = 'John';
function showMessage1(){
userName = 'Bob'
alert('Hello '+ userName);
}
alert(userName);
showMessage1();
alert(userName);
I can understand that in the Function1 showMessage(from, 'Hello');
displays Jane says Hello
and alert(from)
displays Ann
because when I pass the arguments, the function creates a local copy of the values that I passed. I had read that when you have a same-named global and local variable, local shadows global and I think that it happens in Function1 and that's why I get 'Ann' in the last line.
Then since I don't pass on any argument to the Function2, it doesn't create local copy and that's why the value of userName
is equal Bob
and it is displayed in the last line.
EDIT: I rephrase my question: Why do they behave differently (one does not overwrite the global variable and the other does) if the only difference that I see is that one is passed parameters and the other is not?