Happy Coconut
Happy Coconut

Reputation: 1063

Make shorter code in javascript using if else conditions

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.

Upvotes: 2

Views: 83

Answers (2)

Maheer Ali
Maheer Ali

Reputation: 36564

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.

Upvotes: 4

Nina Scholz
Nina Scholz

Reputation: 386550

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;

Upvotes: 4

Related Questions