Equivalent of Ruby unless Statement in JavaScript
-
Create a User-Defined Function to Implement the
unless
Statement in JavaScript -
Negate the
if-else
Statement to Implement theunless
Statement in JavaScript
In Ruby, the conditional statements follow the unless
convention, whereas most programming languages prefer the if-else
condition. The benefit is similar; just the preference is in-built with each language.
Other than Ruby, Perl, CoffeeScript, etc., use the unless
statement.
Here, in our case, we will visualize the application of a general if-else
statement with the definition of unless
. This means we will configure our if-else
statement to behave like an unless
statement.
For the drive, we will generate a function called unless
, and also, we will use direct if-else
to perform the unless
statement’s operation.
Create a User-Defined Function to Implement the unless
Statement in JavaScript
The function we will create here will take on a condition. Also, based on that condition, we will generate another callback function that will infer the function’s satisfiability.
Let’s see the code lines for a better understanding.
Code Snippet:
let unless = (condition, callback) => {
!condition && callback();
} let a = 10;
let b = 20;
unless(a > b, () => {console.log('A should be greater than B')})
Output:
As you can see, the function unless
takes a condition. In our case, the condition is that a is less than b
.
But the unless
function is negated, and when we set the condition as a>b
, it will accept it and trigger the callback function to operate. But according to the scenario of a general if-else
statement, it was not supposed to trigger the callback function as the condition would have fallen under the else
statement.
Negate the if-else
Statement to Implement the unless
Statement in JavaScript
This part is comparatively easier to grasp and implement. All you need is to set the if
work like else
and the else
work like if
.
Whatever condition is applied on if
will be negated beforehand, and thus, the else
will be automatically defined. Let us try the code fence to demonstrate the situation.
Code Snippet:
var a = 42;
var b = 10;
if (!(a > b)) {
console.log('Incorrect');
} else {
console.log('Correct');
}
Output: