1

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

3 Answers 3

3

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);
Sign up to request clarification or add additional context in comments.

Comments

1

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

1 Comment

Formatting tip: Code in lists have to be prefixed by four additional spaces for each list level. So, 8 spaces before your code, in this case.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.