简体   繁体   中英

Variable Declarations with Same Name

If I have this code below:

var greeting = 'Hola';

(function(spanishGreeting, name){
    var spanishGreeting = 'Como estas!';
    spanishGreeting = 'HOLA!'
    console.log(spanishGreeting);
}(greeting,'John'));

console.log(greeting);

Can you explain to if my understanding of the above code is correct? So first inside the IIFE:

var spanishGreeting = 'HOLA!!'; 

That line of code creates a whole new variable with the same name as the parameter that is passed into the IIFE (this new variable declaration has nothing to do with that parameter, spanishGreeting, passed into the IIFE correct?).

Also:

spanishGreeting = 'Como estas!'

will look for the spanishGreeting variable in the current Execution Context of the IIFE. Now the problem is there are two spanishGreeting variables in the current Execution stack. The one in the IIFE parameter and the one I just created:

var spanishGreeting = 'HOLA!!';

How does the JS engine know which one to use?

That line of code creates a whole new variable with the same name as the parameter

No, in fact it doesn't. There is only one scope (the function scope) with one variable of the name spanishGreeting (and a second variable that goes by name ).

The var is ignored, it doesn't create a second variable after the parameter did already introduce it.

When you call the function, the variable is first filled with the argument ( 'Hola' ), then it is overwritten with the value 'Como estas!' , and then with the value 'HOLA!' .


However, there is a situation where you can have two different variables that go by the same name - when they are in different scopes:

var greeting = "Hello outer!";
function greet() {
    var greeting = "Hello inner!";
    console.log(greeting);
}
greet();

How does the JS engine know which one to use?

Here, the JS engine just uses the local variable (which could be declared via var or as a parameter, doesn't make a difference) in the current scope. The inner variable is said to shadow the outer variable.


Btw, if you use the ES6 let keyword to declare your variables, the engine will throw an error if you attempt to re-declare an already defined variable (in the same scope).

i'm not an expert in javascript but. inside a function if your variable name matches with an "outside" variable, it will use the local variable which is inside the function. as far as i know you can declare variables in javascript 2 ways:

var variable1 = 2,
    variable2 = 3;

or..

var variable1 = 1;
var variable2 = 3;

try this:

 var spanishGreeting = 'Como estas!',
     spanishGreeting = 'HOLA!';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM