How to change the value of a variable with a function?

Asked

Viewed 105 times

2

var x = 2

function alterar(x) {
  return x += 2
}

alterar(x)

console.log(x)


console.log(alterar(x))

Why the variable x doesn’t change the value? It only changes when I call the function, but then it goes back to the initial value. Have some way to change a variable through a function?

  • Did any of the answers solve your question? Do you think you can accept one of them? Check out the [tour] how to do this, if you haven’t already. You would help the community by identifying what was the best solution for you. You can accept only one of them. But you can vote on any question or answer you find useful on the entire site

3 answers

2

In general it doesn’t make much sense to do that, but if you really want to do the way of doing it is to pass the value by reference. More details on the subject at Memory allocation in C# - Value types and reference types.

It turns out that JS does not have a way of passing values by reference in a natural way. There are some types of data that are already passed by reference, some immutable, that does not help us because we want to change the value and some changeable, that suits us.

So what we do is we encapsulate a value in a type like this so that the value changes within the function and reflects where the variable was created. It’s not beautiful but it’s the only way to do it in JS, even for having little need.

We can use an object or a array for this since they are types by mutable reference. I will do with array:

function alterar(x) {
    return x[0] += 2;
}
var x = [2];
alterar(x);
console.log(x);
console.log(x[0]);

I put in the Github for future reference.

Almost always this should be done for efficiency reasons, which is not a Javascript goal, so you should not worry about doing this if it is not something natural, the return gives the result you expect, you had already done what you need, there is no need to change the value of the variable thus, only the value was left in the variable itself:

function alterar(x) {
    return x += 2;
}
var x = 2;
x = alterar(x);
console.log(x);

I put in the Github for future reference.

Placed ; because not using it is a bad habit that caught now, there are people who like to teach how to do things that will bring problems, probably to mess with unsuspecting people.

Do not directly change external variables, as was said, works, but is not the right, is like the ; works, but will give problem at some point.

The form held is not ideal because it is changing the value of x place and then return this value, and this case has no reason to change the local value of x, just make the account and return (in another case it might make sense to change the x.

Note that the x local is not the same x global=, even though variables have the same name is not the same variable. See more about What is the difference between scope and lifetime? and Difference between global and local scope. When you do not set a parameter, the x is considered global, there is only it, and creates confusion, so do not.

If you have control over the version you are using it would be even better to use let than var that does not allow the global to be confused with the local. Better still to use Typescript. The let does not work in older versions (which is true in some rare browsers out there). Node programming/Deno is different from doing JS in a browser.

I wanted to show without changing the content of its function, but it is better to do the following:

function alterar(x) {
    return x + 2;
}
var x = 2;
x = alterar(x);
console.log(x);

I put in the Github for future reference.

1

The variable will not change the value this way because when vc passes as argument, javascript is passing a copy of the variable value and not the memory pointer of the variable itself.

To change this external variable to the block, simply change it directly without passing as argument. Return is also not required.


var x = 2

function alterar() {  
  x += 2  
}  

alterar()  
console.log(x)  
alterar()  
console.log(x) 
 

Now, if you still want to change by passing as argument, you can create an object and save the value inside it. And Return would still work.

var objeto = {x: 2}

function alterar(obj) {
    return obj.x += 2
}

console.log(alterar(objeto))
console.log(alterar(objeto))
  • Thank you! You clarified my doubts a lot, but when I should pass parameters to a function?

  • Imagine. For that other question, I think the discussion here would be a little lengthy. It would get more into issues of good practice and code organization. By the little I researched about, declaring variables in javascript as "var" is also no longer recommended nowadays, it is recommended to declare as const or Let. I recommend researching good javascript practices to understand better.

0

You are returning the value and passing the variable as argument. To have the effect you want it would have to be something like:

var x = 2

Function alter() { x += 2; Return x }

alter()

console.log(x)

console.log(change())

  • Thank you very much for the speed of the reply, helped me a lot! I thought if I did not pass the parameter to the function, the program would give as undefined

  • 1

    If the variable exists in the global scope it will work. It is not the best practice for more advanced applications but it works.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.