dzenesiz
dzenesiz

Reputation: 1552

JavaScript assignment in return statement

I've come across a piece of JS code much like this:

let myFn = function(param) {
    if (param > 5)
        return param = 10; // <-- why?
    return param;
}

This code works, which I wouldn't assume if someone asked. But, I see no difference between just returning a value in a regular way:

let p1 = 34;
let p2 = 5;

myFn(p1); // returns 10
myFn(p2); // returns 5
console.log(p1); // 34
console.log(p2); // 5

So, the question is – is there a reason for this at all?

Upvotes: 0

Views: 988

Answers (1)

0stone0
0stone0

Reputation: 44093

No, there is no functional reason to do this.


Since the result of param = 10, is indeed 10, there's no functional difference between;

return param = 10;
return 10;

While benchmarking the code, returning the assingment slows down the code; 100% vs 99.46%.


The only reason I could imagine a developer to choose this option, is to let further developers know that the function is returning a new value of param.

So instead of looking for the function call, the developer could see that the function is overriding the param variable with the new 10 value.

Upvotes: 2

Related Questions