How to evaluate multiple expressions in one line?
We can use the ,
or comma operator to evaluate multiple expressions in one line. It evaluates from left-to-right and returns the value of the last item on the right or the last operand.
let x = 5;
x = (x++ , x = addFive(x), x *= 2, x -= 5, x += 10);
function addFive(num) {
return num + 5;
}
If you log the value of x
it would be 27. First, we increment the value of x it would be 6, then we invoke the function addFive(6)
and pass the 6 as a parameter and assign the result to x
the new value of x
would be 11. After that, we multiply the current value of x
to 2 and assign it to x
the updated value of x
would be 22. Then, we subtract the current value of x
to 5 and assign the result to x
the updated value would be 17. And lastly, we increment the value of x
by 10 and assign the updated value to x
now the value of x
would be 27.