function plus(a){ a=a+10; alert('Вывод функции: ' + a+'<br />'); } var a=25; // Вызовем функцию передав ей в качестве аргумента переменную a plus(a); alert('Значение переменной после вызова функции: '+a+'<br />'); 

Why, if we remove a from function plus (a), then it is output 2 times 35 times, and if left, then 35 and 25 are output.

PS Mat. I am now learning a part, so I ask for help.

  • When a variable is not found in the internal scope (here, the function scope), js recursively turns into the external scope until it reaches the global scope. If there it does not find a variable, it will be created in the global scope, and will continue to be used in a global context. Thus, if а is declared inside the plus function ( var a ), then only the variable а inside the function will be incremented, otherwise it will be used (and incremented!) а from the external scope. - etki

1 answer 1

Do you mean from the ad? Because the scope of a variable declared as an argument , or using var will be the body of the function. Those. the following happens (I'll change the code a bit to make the order clearer):

 //базовая область видимости (родительская для функции plus) var a=25; //в базовой области видимости объявляем "a"=25 function plus(a){ //в области видимости функции plus объявляем "a" a=a+10; //тут ссылка на изначальное "a" пропадает (т.к. использован оператор =) // **локальное** "a" = 35 alert('Вывод функции: ' + a+'<br />'); } // Вызовем функцию передав ей в качестве аргумента переменную a plus(a); //передаем ссылку на a alert('Значение переменной после вызова функции: '+a+'<br />'); 

Second case:

 //базовая область видимости (родительская для функции plus) var a=25; //в базовой области видимости объявляем "a"=25 function plus(){ a=a+10; //тут ссылка на изначальное "a" пропадает (т.к. использован оператор =) // "a" из **базовой области** = 35 alert('Вывод функции: ' + a+'<br />'); } // Вызовем функцию передав ей в качестве аргумента переменную a plus(a); //передаем ссылку на a alert('Значение переменной после вызова функции: '+a+'<br />'); 

To make it clearer about the links, here we are talking about:

 function test(a,b) { a.test=2; //ссылка теряется у того объекта, который непосредственно перед = (.test) b={test: 3}; // ... (b) } var n={test: [1,2,3]},m={test: [4,5,6]}; test(n,m); console.log(n.test,m.test); // 2,[4,5,6]