Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I was wondering if there's a way of changing some variable value with the return of some function. A short-hand-way of doing it.

If I want to add some value to a variable and changing it, we do like that:

let numb = 5;
numb *= 2; // Returns 10

But lets say I have a function that return the double of its argument like this:

function double(a) {
  return a * 2;
}

let numb = 5;
numb = double(numb); // Short hand of doing this line <----
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
170 views
Welcome To Ask or Share your Answers For Others

1 Answer

You need to understand how reference and value parameters work. When you pass in a number or a string to a function that is a value parameter and changing the value of the parameter withing the function has no effect on the variable that was passed in. If the parameter is a reference to an object then changes to properties on that object will then change the variable passed in.

let x = 5;
someFunc(x);

There is no way for someFunc to change x because the value 5 of x was passed into the function, not a reference to x;

let x = { prop: 5 };
someFunc(x);

Now if the body of someFunc changes x.prop then it will also change it to the variable x that was passed in because a reference to an object instance was passed in.

It is the same as assigning variables.

let x = 5;
let y = x;

Now x and y are both 5 but changing y = 6 does not effect x.

let x = { prop: 5 };
let y = x;

Now y is a reference to the same object so y.prop = 6 will change x as well.

All that aside good programming principles and modern functional programming concepts dictate that modifying parameters passed into functions is not good practice.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...