If vs, if in Javascript using an exclamation mark?

The code below tries to print "even" for numbers divisible by 2.

If it is not (test) then (), but not: if (! Test) then () when the checked state is "n% 2". In the code below, it seems that “IF numbers are NOT divisible by 2, they print out“ number equals ”, which does not seem logical.

More generally, what are the advantages of writing an Unless function over using an If statement to specify a condition where we can simply write if (! Condition)?

Any help is greatly appreciated.

function unless(test, then) { if (!test) then(); } function repeat(times, body) { for (var i = 0; i < times; i++) body(i); } repeat(5, function(n) { unless(n % 2, function() { console.log(n, "is even"); }); // → 0 is even // → 2 is even // → 4 is even 
+8
javascript function oop if-statement conditional-statements
source share
2 answers

The proven advantage of this is that the code reads a little English: "If n modulo 2 is non-zero, go to the console, where n is equal."

In my experience, the practical consequence of this is that most programmers will have to double-check what only () actually does before they feel comfortable with it. Since this is not a standard piece of Javascript, they have no way of knowing if it uses! or == true or === 0 or some other, ever slightly different test, if they don't look at the implementation.

My favorite example of this principle is COBOL. This language tried very hard to resemble English, so even non-programmers could use it ... but in fact, both programmers and non-programmers do not seem to like working with it.

+4
source share

There is no benefit if the condition is provided as a string, as in this scenario. You can easily apply the transformation to cancel it as necessary in all cases (for example, adding ! front), and unless extracted from the image means that you need to know less about it.

There may be an advantage if the condition was provided in the form of a callback, for example:

 function test() { return true; } function unless(test, then) { if (!test()) then(); } unless(test, function() { console.log("test failed"); }); 

In this situation, you could not directly pass the negation of test hypothetical onlyIf function, which complements unless , so having both onlyIf and unless can make the code more readable, since it allows you to do this:

 onlyIf(test, function() { console.log("test passed"); }); 

instead of this:

 onlyIf(function() { return !test(); }, function() { console.log("test passed"); }); 

The above situation could be even worse if the callback is given with arguments that need to be decomposed into test .

+1
source share

All Articles