Home > Back-end >  Adding function parameters creates variable shadowing, while no parameters result in reassignment?
Adding function parameters creates variable shadowing, while no parameters result in reassignment?

Time:11-02

Below I have 2 examples, with the only difference being that one function has a parameter while the other doesn't. But Example 1 will log hello to the console, while Example 2 logs hello! to the console.

My question is why does Example 1 log hello while Example 2 logs hello!.

Example 1, I'm uncertain of whats going on. My guess is that in Example 1 we are using variable shadowing. The greet parameter is is initialized to a primitive string hello. The greet parameter are shadowing the greet from line 1. Therefore when we log greet to the console we are logging the greet from the global scope, hello.

I'm not positive but, in Example 2, the function salutation is invoked with the argument 'hello'. Then the global variable greet is reassigned to the value of 'hello' '!'. Therefore when greet is logged to the console, we are logging the value that greet was reassigned to, hello!.

Why does the lack of a greet parameter in the function allow us to log the reassigned value to the console. But when the function has a parameter we log the global variable to the console?

Example 1.

let greet = 'hello';

function salutation(greet) {
    greet = greet   '!';
}

salutation(greet);
console.log(greet); //hello
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

Example 2.

let greet = 'hello';

function salutation() {
    greet = greet   '!';
}

salutation(greet);
console.log(greet); //'hello!'
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

Why does the lack of a greet parameter in the function allow us to log the reassigned value to the console. But when the function has a parameter we log the global variable to the console?

Both examples do log the global variable to the console.

It's just that in the first snippet, there is a local greet variable that gets reassigned, while in the second snippet there is no local variable and it assigns (and accesses) the global variable greet through closure.

CodePudding user response:

The argument to the function is copied by value, so the greet (global) and the greet (local) are completely different. With the below line greet is a copy of the global variable and is only available inside the function, hence local.

function salutation(greet) {
    greet = greet   '!';
}
  • Related