Question

Why the following code does not increase the variable a for 1 ?

var a =5;

function abc(y){
    y++;
}

abc(a);

//a is 5 not 6 why?

but this does

var a = 5;

function abc(){
a++;
}

abc();

//a is 6
Was it helpful?

Solution

Because primitive values are passed by value in JavaScript.

To get the value to be updated, you could put a on an object and take advantage of the fact that objects are passed by reference (well, mostly, really a copy of the reference is passed, but we won't worry about that):

var obj = { a: 5 };

function  abc(o){
   o.a++;
} 

abc(obj);

OTHER TIPS

it takes the argument, but doesn't return any values.

y is just an argument for this I suggest two ways to do this

  1. var a = 10
    
    function increase(){
       a++
    }
    
    increase();
    
  2. var a = 10;
    
    function increase(a){
       return a++; 
    }
    
    a = increase(a);
    

For a beginner's sake,

In simple words, when you call function by abc(a), 'a' is not passed to function abc but its value is copied to 'y'. (Its called pass by value). Since only 'y' in increased, you dont see an updated value of 'a'.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top