2

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.

3
  • 1
    I prefer your current code. It's not very repetitive at all. Maybe golfable, but only at the expensive of readability IMO Commented May 23, 2019 at 9:15
  • 2
    You need to understand that shorter code is necessarily better. Readability is much more important than shorter code. Someone has to maintain your code at some point – it could even be you! And we've all been there where we wonder: what was the original coder thinking!?? Even when we were the one who wrote it a few months/years ago. Commented May 23, 2019 at 9:22
  • What is the practical reason for this "shortening"? Will you use these "cancel" and "request" functions somewhere else? If you do not just obscure the code. Commented May 23, 2019 at 9:27

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Golf: (x = !x) ? cancelAnimationFrame(BI.req) : BI.req = requestAnimationFrame(BI.fn.animate) (no, not seriously proposing anyone actually write this into a code base :P )
4

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;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.