Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
177 views
in Technique[技术] by (71.8m points)

javascript - Short hand to change variable with function

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...