Reputation: 207
I'm learning JS here, and have a question regarding primitive values when passed in as arguments. Say I have a simple function:
var first = 5;
var second = 6;
function func(){
first+=second;
}
func();
alert(first); //outputs 11
So in this case the value of first becomes 11.. But if I try it by passing in first as an argument to the function, first remains 5..
var first = 5;
var second = 6;
function func(first){
first+=second;
}
func(first);
alert(first); //outputs 5
wondering if someone could explain this to me.
Upvotes: 3
Views: 125
Reputation: 11352
It happens because when you call function first()
with no arguments, it uses the global var "first". But when you call function first(first)
, you says to browser that now first is a local variable (only inside the function) and it doesn't make any changes to the global var first
. Here's 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
Upvotes: 4
Reputation: 21099
Mark Linus got your answer right, but I want to add an important note. Primitive values in JavaScript are always passed by value, where Array's and Object's are always passed by reference. Example:
var first = [ 'a', 'b' ];
function func( arr ) {
arr.push( 'c' );
}
func( first );
alert( first.join( ',' )); // output is 'a,b,c'
It gets more complicated if you have Objects in Objects or Arrays. Just remember that an alteration will affect all instances in your program.
Upvotes: 0
Reputation: 150263
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.
Upvotes: 1
Reputation: 53311
Due to Javascript's scoping, the scoped variable first
is overriding the global variable first. In other words, you're adding second
to the scoped version of first
inside your function (which is scoped because you're declaring it inside the function), and the global version of first
is unaffected.
If you remove the first
's declaration from the function, Javascript goes for the next version of first
it can find--in this case, the global one.
Upvotes: 2