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.
It happens because when you call
function first()with no arguments, it uses the global var “first”. But when you callfunction 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 varfirst. Here’s the code: