Variable declarations with the 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 if I understood the above code correctly? So first inside IIFE:

var spanishGreeting = 'HOLA!!'; 

This line of code creates a whole new variable with the same name as the parameter that is passed to IIFE (does this new variable declaration have nothing to do with this parameter, spanishGreeting, correctly passed to IIFE?).

also:

spanishGreeting = 'Como estas!'

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

var spanishGreeting = 'HOLA!!';

How does the JS engine know which one to use?

+4
source share
2 answers

,

, . ( ) spanishGreeting ( , name).

var , , .

, ('Hola'), 'Como estas!', 'HOLA!'.


, , - :

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

JS , ?

JS- ( ​​ var , ) . .


Btw, ES6 let , , , -declare ( ).

+2

javascript, . , "" , , . , javascript :

var variable1 = 2,
    variable2 = 3;

..

var variable1 = 1;
var variable2 = 3;

:

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

Source: https://habr.com/ru/post/1612988/


All Articles