Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

JavaScript – How to modify 'variable' inside function so that it does not revert to original value after function termination?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading