Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make shorter code in javascript using if else conditions

Tags:

javascript

I know about the ternary expression in javascript. However i don't know how to make this piece of code shorter.

if (x == false) {
    x = true;
    cancelAnimationFrame(BI.req);
}
else {
    x = false;
    BI.req = requestAnimationFrame(BI.fn.animate);
}

I guess I can make two separate functions and use them with the ternary expression. Something like this:

function cancel() {
    x = true;
    cancelAnimationFrame(BI.req);
}
function request() {
    x = false;
    BI.req = requestAnimationFrame(BI.fn.animate);
}

x == false ? cancel() : request();

But this doesn't feel like I am really making my code much shorter. Any suggestions will be much appreciated.

like image 711
Happy Coconut Avatar asked Apr 13 '26 04:04

Happy Coconut


2 Answers

You can use ternary for the functions. And use ! operator to set x

x ? BI.req = requestAnimationFrame(BI.fn.animate) : cancelAnimationFrame(BI.req)
x = !x 

Or even more shorter

(x = !x) ? cancelAnimationFrame(BI.req) : BI.req = requestAnimationFrame(BI.fn.animate)

The question was about shorter code so I answered this. Otherwise your own snippet is fine or consider Nina Answers because these two lines are completely non-readable.

You shouldn't use ternary operator like that too. Don't use ternary operator instead of if-else whenever there are two or move expressions in any block.

like image 168
Maheer Ali Avatar answered Apr 15 '26 18:04

Maheer Ali


You could shorten it a bit by moving the assignment to the bottom and use a positive check.

if (x) {
    BI.req = requestAnimationFrame(BI.fn.animate);
} else {
    cancelAnimationFrame(BI.req);
}
x = !x;
like image 22
Nina Scholz Avatar answered Apr 15 '26 18:04

Nina Scholz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!