Aljoša Srebotnjak
Aljoša Srebotnjak

Reputation: 1331

javascript arguments for beginner

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

Upvotes: 1

Views: 82

Answers (3)

Jashwant
Jashwant

Reputation: 29015

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'.

Upvotes: 0

nivanka
nivanka

Reputation: 1372

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);
    

Upvotes: 1

Adam Rackis
Adam Rackis

Reputation: 83356

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);

Upvotes: 3

Related Questions