Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the JavaScript equivalent of Ruby's "unless"?

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)?

like image 726
Choylton B. Higginbottom Avatar asked Sep 30 '16 20:09

Choylton B. Higginbottom


People also ask

Is there unless in Javascript?

The unless() method is executes the callback provided when false is evaluated by the first argument given to the method.

What is unless Ruby?

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.

What do you mean by unless 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.

Do not use unless With else?

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.


2 Answers

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")})
like image 56
sathish1409 Avatar answered Sep 20 '22 13:09

sathish1409


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');
}
like image 26
Patrick McElhaney Avatar answered Sep 21 '22 13:09

Patrick McElhaney