Ruby has a handy unless conditional, which is "The negative equivalent of if."
Is there a way to do a "negative if" in JavaScript that's more semantic than if (!condition)
?
The unless() method is executes the callback provided when false is evaluated by the first argument given to the method.
Ruby provides a special statement which is referred as unless statement. This statement is executed when the given condition is false. It is opposite of if statement.
You use unless to introduce the only circumstances in which an event you are mentioning will not take place or in which a statement you are making is not true.
There is nothing stopping anyone from using unless - else . It is perfectly valid. But the else part of unless-else is a double negative. In some cases, unless is easy to comprehend.
Here's the hack :P
let unless = (condition,callback)=>{!condition && callback();}
let a = 10;
let b = 20;
unless(a > b,()=>{console.log("A should be greater than B")})
No, there's no such control structure. One thing you can do to make code more readable is wrap the negation in a function.
function baconIsTooThin () {
return !baconIsChunky();
}
if (baconIsTooThin()) {
...
}
Or you may want to use CoffeeScript, which makes JavaScript look more like Ruby (and has unless
) and compiles down to plain JavaScript.
Example:
// CoffeeScript
unless (foo)
alert('bar')
// Compiled JavaScript
if (!foo) {
alert('bar');
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With