Primitives as function arguments in javascript

I study JS here and ask a question about primitive values ​​when passing as arguments. Let's say I have a simple function:

var first = 5;
var second = 6;

function func(){
    first+=second;
}
func();
alert(first); //outputs 11

Thus, in this case, the value of the first is 11 .. But if I try it, passing it first as an argument to the function, first 5 will remain ..

var first = 5;
var second = 6;

function func(first){
    first+=second;
}
func(first);
alert(first); //outputs 5

I wonder if anyone can explain this to me.

+3
source share
4 answers

This is because when you call function first()without arguments, it uses the global var "first". But when you call function first(first), you tell the browser that now is the first local variable (only inside the function), and it does not make any changes to the global var first. Here is the code:

var first = 5;
var second = 6;
function func(first){
    first += second; //Local var "first" + global var "second"
    alert(first); //Local var, outputs 11
}
func(first);
alert(first); //Global var, outputs 5
+4

- Javascript first . , second first ( , ), first .

first , Javascript first, - .

+2
var first= 5;
var second= 6;

function func(first){

first+=second; // change the local first variable

}
func(first);
alert(first);//outputs 5 - the outer variable wasn't changed.

var first= 5; // global var
var second= 6;

function func(){ // first wasn't defined in the inner scope.

first+=second; // change the global bar

}
func();
alert(first);//outputs 11 - the outer variable was changed.
+1
, . JavaScript , Array Object . :
var first = [ 'a', 'b' ];

function func( arr ) {
    arr.push( 'c' );
}

func( first );

alert( first.join( ',' )); // output is 'a,b,c'

, . , .

0

All Articles