Unless vs if in Javascript with use of exclamation point? - javascript

The code below attempts to print out "is even" for numbers divisible by 2.
Should it not be if (test) then() rather than: if (!test) then(), when condition tested is "n % 2". The code below seems to read "IF numbers are NOT divisible by 2, print out 'number is even' ", which does not seem logical.
More generally speaking, what are the advantages of writing an Unless function over using an If statement in specifying condition, when what we could do is simply write if (!condition)?
Any help is much 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

The arguable advantage of this is that the code reads slightly more like English: "Unless n modulo 2 is nonzero, log to the console that n is even."
In my experience, the practical consequence of this is that most programmers will have to go double-check what unless() actually does before they feel comfortable with it. Because it's not a standard piece of Javascript, they have no way of knowing whether it uses ! or ==true or ===0 or some other ever-so-slightly different test, unless they go look at the implementation.
My favorite example of this principle is COBOL. That language tried very hard to resemble English, so that even non-programmers could use it...but in reality both programmers and non-programmers seem to hate working with it.

There are no advantages if the condition is provided inline as in this scenario. You can easily apply a transformation to negate it as appropriate in all cases (e.g. adding a ! in front), and taking unless out of the picture means there's one less thing the reader has to know about.
There could be an advantage if the condition was provided in the form of a callback, e.g.:
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 to a hypothetical function onlyIf that is complementary to unless, so having both onlyIf and unless can make the code more readable because 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 arguments that need to be propagated into test.

I agree with Mahdi that this likely came about in reaction to an intentionally strange example of callbacks, but for the sake of completeness—plus a particular interest in negation—there is one more option:
if(test){}else{then}
This is shorter than unless() even after the arrival of arrow functions. It also keeps the metaphor of having a "free pass" on the expression. I think any further attempt to contend with the ! or ?: operator for grammatical reasons, realistically, would require the language to allow:
else(test){then}
Given this, I would still pick the former for flexibility, and for existing. :)

Related

How do I write a clean conditional statement

This may be a dumb question but what is an easy way to write a clean condition statement, for example lets say if I have a conditional statement where I only want it to happen before a block of code if it meets the requirement and if it doesn't then I want it to happen after the block of code. But it must happen in that order
EDIT
This code is NOT broken.. I was simply asking if there was a better way of structuring this conditional statement and I found out that putting the //random code in a helper method and combining the two if's into an else if would solve it. See my answer below.
if(number === 250){
// sameMethod()
}
//random code
if(number !== 250){
// sameMethod()
}
Solution
function helper() {
//random code
}
if(number !== 250){
helper()
// same code
} else {
// same code
helper()
}
if(number == 250){
// sameMethod()
}
//random code
if(number != 250){
// sameMethod()
}
For this, and based on the information at hand, I would recommend keeping the code as is. The way you have written this code, an if-else block would have a serious impact on the flow of your application.
Assume that randomCode is a method call, which performs the next operation:
function randomCode() {
this.number += 5;
}
and you start the code with the state of your application having the value of number as 245.
if ( number == 250 ) { // conditions 245 == 250 evaluates to false
// sameMethod -> will not be executed
}
randomCode(); // increases the value of number with 5
if ( number != 250 ) { // condition 250 != 250 evaluates to false
// sameMethod -> will not be executed
}
Just slapping an if-else, like this:
if ( number == 250 ) { // condition 245 == 250 evaluates to false
// sameMethod
} else {
randomCode();
// sameMethod -> here it will be executed, even though number now is 250. Change in behaviour
}
So, there are two things to consider: either the example code you posted was the correct flow, making it correct (but might end up in executing sameMethod twice, or not at all, since the value of number could be altered in the randomCode part, or both sameMethod and randomCode have to be executed (exactly) once, depending on that condition.
If so, the original (pseudo?) code was faultive, but the result would indeed come to:
if ( number == 250 ) {
sameMethod();
randomCode();
} else {
randomCode();
sameMethod();
}
This is where monads and all that jazz show their ugly mugs.
Assuming you are talking about java, you could for example write a runSequentially method that results in letting you write:
runSequentially(() -> sameMethod(), () -> {
// random code
}, number != 250);
Where runSequentially will first run the first Runnable, then the second Runnable - unless the condition is false, in which case it runs the second, then the first.
In java, this is not, however, local mutable variable, checked exception, and control flow transparent which are sufficient downsides that I'm not sure this is a good idea. Especially considering that apparently execution order matters which usually suggests mutating state. But, if you insist, it'd be something like:
public static void runSequentially(Runnable a, Runnable b, boolean flipOrder) {
if (flipOrder) { b.run(); a.run(); }
else { a.run(); b.run(); }
}
Javascript is a lot more laissez-faire (and a totally different language; did you tag it because perhaps you were unaware that 'java' and 'javascript' are completely unrelated? It's a common mistake - in that case, disregard this bit), and doesn't suffer from the transparency issues as much. Javascript has no checked exceptions, javascript lets you mutate outer state (there are some WTFs in javascript-the-language about this, but that's a separate issue). The biggest issue is control flow (you can't as easily break/continue loops in the 'outer' code from within these closures).
Going back to java for a moment, using lambdas (closures) in contexts where:
The lambda is run 'in-line', that is, you pass the lambda to some method, and once that method returns, the lambda is 'forgotten about' by said method: That method did not store the lambda in a field, did not pass it to another thread, did not pass it to other code that is going to store it in a field or pass it to another thread).
The code in the lambda is not designed 'functional style' (e.g. it mutates state or does a bunch of I/O), then
you're probably messing up. Lambdas really suck in that environment, those transparency issues are grating then. Note that if the lambda does 'travel' (is stored / moved to another thread), that lack of transparency is in fact a great thing because those 3 'transparencies' become bizarre braintwisters - best to just not allow them.
That's why I recommend against this, if you're writing java. But now you know how one would.
Thanks for all the advice, I should've been more clear about the language since I thought this was a fairly simple solution that might work in both Java and Javascript. I ended up just putting the "random code" in a helper function.
function helper() {
//random code
}
if(number !== 250){
helper()
// same code
} else {
// same code
helper()
}
Basically the idea was that, the order of which block of code that gets executed mattered depending on a fixed variable. It was messy without a helper function due to duplicated code so this simple solution fixed it. Let me know if you guys think of a more clever way! Thanks

Which is more efficient in a function: conditional execution or conditional exit?

I would really hear some opinions on which of the following solutions is more efficient in JavaScript/TypeScript:
function whatever(param) {
if (param === x) {
doStuff();
}
}
or
function whatever(param) {
if (param !== x) { return false; }
doStuff();
}
Obviously the second one reduces the number of blocks and improves code readability, but does it offer any benefits or drawbacks compared to the first one?
In assembly you'd write both as:
// first
whatever:
CP x, param
JP nz, whatever2
CALL doStuff
whatever2:
RET
// second:
whatever:
CP x, param
JP z, whatever2
RET
whatever2:
CALL doStuff
RET
So while the first one uses 4 instructions, the second uses 5. So in case the JS engine is able to optimize it down to this optimal bytecode (very unlikely, but it makes estimations easier), the second one will be 1 tick slower, which is less than a nanosecond.
Here is a test where I run the comparison 10000 times.
The difference is pretty much non-existant.
There is no significant difference in efficiency, even if you have more than one of these preconditions in your function. No matter what language you use. Some compilers will probably even generate the same machine instructions from both versions.
Stop thinking about efficiency too much. Think about readability and maintainability!
It depends on the use case here, I don't think there is much difference in the context of performance or code readability.
I would personally go with the second approach as it also reduces indentations. Indentation gives me a clear indication of initialization of newer block. If I notice a new indent, I would assume there should be a for loop here or an if statement.
If the code is part of the main flow or the most common flow, I wouldn't want that to be further indented.
Again, All this is my personal style guide rules which have helped me to be able to deduce the code logic faster.

What is the Definition of Recursion

So, we all know recursive functions, right? But what exactly is it, that makes a function recursive? I had a small discussion in the comment section of another question (Lightening effect with javascript) that kind of challenged my view of recursive functions but it also left me with a quite unsatisfying lack of proper definition.
My personal definition of recursive functions so far was the following:
A function is recursive if it directly or indirectly invokes itself
Note: I will provide JavaScript code for the following examples, but I'm sure they are pretty universal.
A simple example for such a recursive function could be this:
function a() {
a();
}
but also this:
function a() {
b();
}
function b() {
a();
}
or even this:
function a() {
setTimeout(a, 1000);
}
None of those functions computes anything but I would have still considered them recursive just because they invoke themselves.
One thing that came up was, that the third example is not recursive because it uses setTimeout and therefor the stack is unwound. It also isn't recursive because after returning from the nth invocation it doesn't give back control to the n-1th invocation.
Another point, that was raised, was that none of those functions were recursive because they all don't compute an actual problem in a recursive way. Meaning that a problem has to be solved by dividing it in smaller and smaller instances. Here the quoted Wikipedia article:
Recursion in computer programming is exemplified when a function is
defined in terms of simpler, often smaller versions of itself. The
solution to the problem is then devised by combining the solutions
obtained from the simpler versions of the problem.
So this is recursive:
function fac(n) {
if (n <= 0) {
return 1;
}
return n * fac(n - 1);
}
But this wouldn't be:
function fac(n) {
if (n <= 0) {
return 1;
}
console.log(n);
fac(n - 1);
}
So what is the proper definition of a recursive function? Is there any at all or is it really just a philosophical question? What features must a function have, in order to be classified recursive?
Recursion is simply defining a problem in terms of a simpler case (simpler meaning "closer" to the terminating condition, not necessarily actually simpler) of that problem, down to the point where the simplest case is a known one (the terminating condition alluded to earlier). So, for example, the perennial factorial function has a terminating condition:
f(1) = 1
and the definition of the problem in terms of a simpler one:
f(n) = n * f(n - 1), for n > 1
The best explanation of it that I ever heard was this:
If you're Donald Knuth, you understand what it is.
Otherwise, find someone closer to Donald and ask them.
I wouldn't call the setTimeout one recursion because a is not actually calling itself. Instead, it's asking the "system" to call it at some later date.
It's also important to have the terminating condition in there somewhere. Without that, it's still recursion but it's infinite recursion, no different to infinite loops like:
for (i = 0; i < 10; j++) {}
and hence unlikely to be any good for anything other than testing what happens when your stack overflows :-)
Definition of Recursion? Read this line again until you get it.
(A selfcalling function with an abort criterium to prevent infinite looping).
Recursion is the name that was given to function that calls itself. Now whether the function calls itself infinitely or not.. it is still a Recursion.
It is not necessarily that the problem is divided into sub-problems. However, in computer science; The term Recursion refers to a technique that is used to solve a problem, by breaking the problem into sub-problems and usually the problem is finite.
One more point, Recursion is implemented using Stack. Each function call is piled on top of the other in the stack, until the last call meets the base condition, then the functions in the stack are executed from top to bottom.
However, if there is no base condition or the base condition is never to be satisfied. then infinite calls to the function will be pushed to the stack causing the memory to be filled up and a stackOverFlow exception will be thrown and OS handles it by terminating the program.
In Regard to setTimeout() It is an asynchronous call and is not related to recursion, it is an independent call as the caller function doesn't depend on the called one whether it is the same function being called or another.
From Wikipedia that you have posted:
Recursion in computer programming is exemplified when a function is defined in terms of simpler, often smaller versions of itself. The solution to the problem is then devised by combining the solutions obtained from the simpler versions of the problem.
So. There is a problem, and there is a solution. There is a function that call itself minimizing the main problem. This function is recursive.
Case:
function a() {
a();
}
there is no problem, there is nothing to minimize, there is no solution. It's not recursive for me. It's just an infinite loop.
So another example:
function a(n) {
if(n<.5) {
return n+a(Math.random());
}else {
return n;
}
}
console.log(a(.3));
Is this recursive?
No.
There is maybe a problem, but the solution is not found minimzing the main problem. Simple it call itself randomly until some flag is true. Again, it's a loop.
The same happens with a setTimeout or setInterval (the solution of problem will depend from system call).

if..else vs if(){return} [duplicate]

This question already has answers here:
Using 'return' instead of 'else' in JavaScript
(13 answers)
Closed 5 years ago.
In the following example - given that the return value isn't of any importance - is there a reason to prefer either method over the other?
// Method 1
function (a, b) {
if (a == b){
// I'm just interested in
// the stuff happening here
} else {
// or here
}
return true;
}
// Method 2
function (a, b) {
if (a == b){
// I'm just interested in
// the stuff happening here
return true;
}
// or here
return true;
}
It seems that best practices (mostly by places I've worked for) is to set default values at the top of a method or function and only change those values if some condition occurs. Thus, the use of else is not needed so Method 2 is preferred.
Since the example is JavaScript, special attention needs to be paid in regards to code size. So Method 2 would create less code for the same functionality, furthering its argument as the preferred.
However, if you have more than 2 possible conditions, an else or else if cannot be avoided. However, most places I've worked prefer a Switch Case in these situations.
I would prefer Method 1 because it is less confusing to read. Also, less duplicate code.
I would base my decision on clarity of code and readability, i.e.:
Choose method 1 when you need to do more stuff in the block after the if-block.
Choose method 2 when you only need two blocks of code, it's then clearer to read
Choose method 1 again in cases where you explicitly think your readers wouldn't understand your cryptic code without the word "else"; this is common when the blocks become larger than a few lines.
Many of today's programmers consider less indentation easier to read and I agree. In which case general preference should go to using the second method.
I would recommend method 1 as it is more readable and self documented.
Any modern browser's interpreter should eliminate any performance advantage in either direction.
There are a couple of reasons method 1 is preferable that haven't been mentioned yet. Having a single point of exit makes any future modifications that require an action common to both branches easier and less likely to be buggy (because the author missed the early return. Similarly, in some cases it makes debugging easier, by providing a common place to put a breakpoint or alert().
Readability here really depends on the role of the function.
If this function will ALWAYS return true, then I would prefer the Method 1 It is clear because it only returns in one place, and it is easy to see it will always be true.
In the above case, Method 2 is more confusing. It returns in multiple places, and is more confusing thusly. Consider a developer unnecessarily traversing possible branches and then seeing how they affect the return value. In this simple case, it is not as big of a deal, but when you get more elaborate conditionals, I would really avoid this approach.
I would only use Method 2 if you have very little code in the if block. Such as something that would deal with an edge case.
Hope that helps.

Where to perform argument validation in JavaScript?

Yeah, read properly. In the last time I saw different patterns of argument validation in JavaScript (functions) and wondered which of them would be best-practice. At first I'll show two example code snippets. The first shows an (in my words) "immediate" argument/condition validation and the second one a "delayed" validation. Each of them affect the appearance of following code in different ways. Up to now I always used the "immediate" validation. But slowly I am getting doubtful if it's reasonable to force the whole following code into such conditional blocks. Please tell me what you think and what might be the "best" pattern.
And what about the place where variables are declared? A few times I read, that ALL variables should be declared on to of the method, before they're actually used. Is this correct? Because I think that it is useless to declare variables before it is sure that they'll be actually used (maybe invalid arguments force the throw of an Exception), I moved the variable-declaration-part beyond the argument/condition validation part. Is this advisable?
Thanks!
First example:
if ( colorStops.constructor === Array
&& colorStops.length
&& colorStops.every(function(c) {
return c instanceof ColorStop
}))
{
var privateVar1 = "foo",
privateVar2 = "bar",
privateVar3 = "tutifrutti";
// here goes the code
}
else {
throw new TypeError("GradientCanvasFacade: cannot add Colors; " +
"invalid arguments received");
}
Second example:
if (cg instanceof ColorGradient) {
throw new TypeError("PresetManager: Cannot add preset; " +
"invalid arguments received");
}
var privateVar1 = "foo",
privateVar2 = "bar",
privateVar3 = "tutifrutti";
// here goes the code
// Here goes the code that get executed when no explicit
// return took place ==> all preconditions fulfilled
Since JavaScript variables are scoped to the declaring function and not to the block as most other languages, declaring variables at the beginning of the function makes alot of sense.
function someFunc()
{
if (1==1)
{
var x = 1;
}
else
{
var x = 2;
}
return x
}
Now imagine a function a lot more complex, to me atleast, declaring x at the beginning makes alot of sense. For variables generally bound to a block (like iterator variables or collections) I still declare them in the block though.
I would definitely go for your second example not because it fails earlier, because really it doesn't, but because it's easier to remove and add validations this way without breaking a complicated if structure.
I'd go with the second, simply because it's easier to read. Also, with the first, if your function is very long, someone looking at the bottom, will wonder what that } is for, and have to hop up to the top to see.
Also the scoping of variables is very clear, even for someone who forgets that javascript has weird scoping rules.
Also, as mentioned by Martijn, the second method makes it a lot easier to check for various errors, ie each can have their own if statement and so on.
if (some condition) {
if (some other condition based in the first) {
if (another condition based in 1st and 2nd) {
do_job();
} else?
} else?
} else?
Where to put the else block? After every if or after the last?
It seems absolutely more readable the second choise

Categories