Does it matter which way I write recursion? [closed] - javascript

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed last month.
Improve this question
I happened to review recursion again and noticed that some people write recursion with and if else statement. The if being the base case and the else having the recursive call. However, I have been only using an if for the base case with no else, and just the recursive call under it. See below.
//using else
if(n === 0) return 0;
else if(n === 1) return 1;
else return fib(n - 1) + fib(n - 2);
//versus no else
if(n === 0) return 0;
else if(n === 1) return 1;
return fib(n - 1) + fib(n - 2);
Logically they are equivalent because of the returns. There is no difference in the result. But is there any reason to do one over the other? I feel like sometimes I flop between them, but I default to not using the else.

This is a purely stylistic question so I will offer a purely stylistic answer.
The general question is, should I write
{
if (x) {
y();
return;
}
z();
}
or
{
if (x) {
y();
} else {
z();
}
}
Well, what is the purpose of the function? Is z the ultimate purpose of the function, and the condition x and the y basically handling some edge case? Or are y and z two alternative modes, roughly equivalent?
If the first, if z is the “real” code, then you should try x and y as a guard clause — it’s just some uninteresting case to dispose of before getting to the meat of the function; y might even be empty. Use an early return.
In the second case, y and z are symmetric, so they should be treated symmetrically: one should be the “then” and the other the “else”.
Your case is recursion, which is not exactly either of the two cases I mentioned, but the function has two states — the “termination” state, where this is the last step, and the “recursion” state — and they are very different.
Therefore I would write them differently. The termination case would go in an if block, with a triumphant return statement. The rest of the function would be the recursion case.

It doesn't matter in this case since each if statement is returning something. This would be a more stylistic approach; if this matters, one would consider using brackets. But it only matters if someone should use an else statement is if one wants to run the code in the else statement ONLY if the if statement(s) are false.

Related

How to differentiate between closure and currying in javascript [duplicate]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
It would be very helpful, if someone explains the working of a curry function. I have read many examples, but not able to grasp it properly. Is it anyhow related to closure.
Currying is just technique, that can make use of any language feature (e.g. closures) to achieve the desired result, but it is not defined what language feature has to be used. As of that currying does not require to make use of closures (but in most of the cases closures will be used)
Here a little example of the usage of currying, with and without the usage of closure.
With the use closure:
function addition(x,y) {
if (typeof y === "undefined" ) {
return function (y) {
return x + y;
}
}
return x + y;
}
var additionRemaining = addition(3); // Currying
additionRemaining(5);//add 5 to 3
With the use of new Function instead of closure (partial evaluation):
function addition(x,y) {
if (typeof y === "undefined" ) {
return new Function('y','return '+x+' + y;');
}
return x + y;
}
var additionRemaining = addition(3); // Currying
additionRemaining(5);//add 5 to 3

What's a good return value in case a function fails? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
Had this problem already several times: I've got to program a function in JavaScript.
In know how to check if the required parameter has been assigned. I also know how to check data-type correction.
When one of the checks fail I like to terminate the function by using return.
The thing I'm unsure about: What value shall I return in case of failure?
Some people use 0 or -1 ...
I've seen people doing something like ...
if (x === undefined) return
... what results in the return of undefined.
Or shall I throw an exception instead of using a return?
The return value has no meaning until you decide to handle it. This means you can make them whatever you like, as long as you are handling them accordingly from the other side. for example:
function foo(){
if(goodstuff){
//do good stuff
}else{
return 1;
}
}
Returning 1 here doesn't inherently mean anything. 1 or -1 are simply common return values for an error. The key is for you to handle the "error" when the function is called:
var success = foo();
if( success === 1){
alert('error');
}else{
//do stuff
}
you can return false, null, 0, "oopsies" or whatever other value makes sense for your situation. The only thing that matters is that you handle it accordingly. Generally returning false or 0 makes for the simplest check, which is why they are commonly used.
To answer your other question, simply doing return; will just terminate the function without sending back a value. This is useful if you don't necessarily need to return an error code, but simply just don't want the rest of the code in the function to execute. For example:
function bar(){
if(notAWinner){
return;
}
alert('you win a million dollars!');
}

One-line if vs && in JavaScript [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
Is there any meaningful difference between
condition && console.log("this may run");
and
if (condition) console.log("this may run);
If not, which is a best practice?
You should use the second.
Your code should say what it means. That is what is meant by writing "semantic" code. If you are writing an if condition, then you should use the if statement, because that's what it is there for. The && is, semantically, a logical and, which should be used in cases where you are interested in the logical value resulting from the logical conjunction of two values.
Writing semantic code, as other answers have suggested, makes it easier to write and understand and maintain. As far as this comment goes:
If someone else may need to read or maintain it, then use the second.
Remember that "you six months from now" is "someone else".
Here are some specific reason for using if when you mean if:
If you want to add an else clause, you can just add it. If you have written a && b then you will have to rewrite it as a ? b : c.
Assuming you have used curly braces, as in if (a) { b; }, then you can easily add another step to the body, by writing if (a) { b; c; }. If you had written a && b, then you would need to rewrite this as a && (b, c) or something equivalent; this will not even be possible in some cases, if c cannot function as an expression.
Some linters will (reasonably) complain about a && b.
Note that minifiers will typically convert your second example into the first, so if your rationale for using && is to save bytes, they will be saved anyway by the minifier.
There is no difference as such, but you can say that the former one is the shorthand notation of the later one.
I would suggest you to use the later condition, it makes the code more explainable, producing the same results and with the almost the same number of characters.
If only you may ever maintain the code, then use the one you like.
If someone else may need to read or maintain it, then use the second.

Is it typical for a Javascript function to return a value of undefined intentionally? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
I'm new to Javascript and am wondering if intentionally returning a value of undefined from a function is a common practice.
For example, should a divide() function be implemented like this:
var divide1 = function (x, y) {
if (y === 0) {
return undefined;
}
return x/y;
};
or like this?
var divide2 = function (x, y) {
if (y === 0) {
throw new Error("Can't divide by 0");
}
return x/y;
};
I assume that returning undefined is typically reserved for functions with no return values (equivalent of void in Java or C#).
It's the default:
function foo() {}
console.log(foo());
But it turned out it's not a good choice. Code which can run into an exceptional state shouldn't do so silently. A lot of errors in JavaScript slip through the cracks because the code doesn't break violently when something goes wrong.
So unless you're an exceptional good developer and you can guarantee that everyone who will ever touch this code is on the same level and you never make mistakes, you can return undefined. I, myself, would throw an exception.
Turns out I'm not a good-enough developer :-)
I assume that returning undefined is typically reserved for functions with no return values (equivalent of void in Java or C#).
As in Java or C#, you can also write return;.
These three functions are returning the same thing:
function VOID () {
return;
}
function VOID () {
return undefined;
}
function VOID () {
}

Ternary Statements in Javascript: pitfalls of no assignment? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
Sometimes I use ternary statements to simplify & reduce the length of my code.
Ternary statements are traditionally used to assign a value to a variable, but in JS I can also write ternary statements with no assignment to execute differing outcomes based on the boolean response to the question - example:
anyVariable > someValue ?
funcOne(anyVariable):
funcTwo(anyVariable);
This code throws no errors, but jsLint complains that it saw an expression where it expected an assignment or function call.
Are there any pitfalls or potential issues I should be aware of when using ternary statements (in Javascript) in this fashion?
There should not be any pitfalls in this fashion. Consider the following statement -
b = a = 10;
we can omit the "b=" portion of the statement without any issues. And its the same case for the ternary statements.
Generally you should avoid this type of use because an error in previous lines may cause problem with the later code. But if you use if-else then you can avoid such problems.
// user made a typo on the first line. but this code has correct syntax
b = 10 +
a > 10 ? fun(20) : fun(0);
// same scenario using if-else will generate a compilation error which is preferred.
b = 10 +
if (a>10) {
fun(20);
}
else {
fun(0);
}
JS(L|H)int is going to complain about that because it's just a expression and not a statement. In cases like this, it's "better" (argumentative) to use an if:
if(anyVariable > someValue){
funcOne(anyVariable);
} else {
funcTwo(anyVariable);
}
edit
If terseness is a goal you can always omit the curly braces:
if(anyVariable > someValue) funcOne(anyVariable)
else funcTwo(anyVariable);
/edit
The bonus here is that your code is more readable (since it's all assignments or function calls), and if you need to extend or do more than one operation in each clause, you're set up for it.
Where the ternary operator is used well, however, is in assignments:
var thisVariable = someValue > thatValue ? someValue : thatValue;
That will pass the linter, and the statement, while terse, is still pretty readable, however, when testing against "falsey" values, I do prefer:
var thisVariable = someValue || thatValue;
If someValue is "falsey", it will set thisVariable to thatValue.
I'd avoid it, if you use it incorrectly then it'll cause errors (I've seen invalid left hand assignment amongst others). If you're using a good minifier (such as Uglify), it'll do all this for you when running your build process - which keeps your development code readable and easy.
I'd stick with using it for assignment only.

Categories

Resources