Home > other >  JavaScript - How to modify 'variable' inside function so that it does not revert to origin
JavaScript - How to modify 'variable' inside function so that it does not revert to origin

Time:10-07

I have a script like this:

function changeValue(x){
    x = 30;
}

let a = 3;
changeValue(a);
console.log(a);

The above code outputs 3, but the expected output is 30.
Now I'm aware why this is happening, but how do I modify my code so that the changes made do not revert after the changeValue function ends?
I have read that there are no explicit pointers in JS and I don't want to alter the value using the global variable name or by using the object approach. Is there any other way to solve the problem?
Thank you

CodePudding user response:

The best way would be to use return, because x isn't an object, it's just a variable. It is discarded after the function.

Using Return:

function changeValue(x){
    return 30;
}

let a = changeValue(3);
changeValue(a);
console.log("Output Is:", a);

CodePudding user response:

In JavaScript, all primitive types (integers, floats, etc) are passed by value, so as other people said, for your specific use case, it's better to return the value like this:

function returnValue(x) {
  return x * 10
}

let a = 3;
a = returnValue(a);
console.log(a);

However, if you really want to change the argument and NOT return, you need to do it with pass by reference. As I said above, it's not possible with primitive data types but is possible with objects:

function changeValue(x) {
  x.value = x.value * 10;
}

let a = { value: 3 };
changeValue(a);
console.log(a.value);

  • Related