When should I use return? - javascript

It's a petty basic question which seems I don't fully understand,
What exactly is the use of return? In what cases should I use it?
What would the difference between these code samples be?
function fun(text) {
console.log(text);
};
function fun(text) {
return console.log(text);
};
To be clear: I know what return does, I just don't feel like I fully understand it's purpose and when should I use it

You should use return if your function needs to, well, return anything to its caller. In your example, it's not necessary to use return because console.log already does what you want it to do. But, if your function calculates something (for example a mathematical operation like adding the first two params it receives), it's logical it "returns" the result, like this:
function add(a, b) {
return a + b;
}
This way the function caller can use the result for whatever it's doing.

return is used to send a value back to where's it's called from. You use it if you want to return a value.
If you don't have a return statement, it's the same as return undefined. console.log returns undefined, so return console.log(text) returns undefined.
So, only return if you want to get a value from the function.

return exits from the function, possibly with a value.
Lets say we have these two functions:
function foo(a, b) {
return a + b;
}
function bar(a) {
if (a > 10)
return;
// Do something with 'a'
}
If the first function, foo, return exits the function and the result of calling the function (e.g. var c = foo(1, 2)) is the result of the expression given to return, in this case the sum of a and b.
In the second function, bar, return is used to exit the function if a is larger than 10, but otherwise execution of the function continues. It doesn't return with a value like foo, so using bar as part of an expression could result in an error.

return halts the execution of the function and defines the value that is returned as the result of calling the function.

Related

Why must I put a return in front of a function when using it recursively to get the proper output?

I'm going through the Eloquent Javascript book and one of the exercises is to calculate whether a number is odd or even by creating a recursive function.
My code was this:
function isEven(n) {
if (n == 0)
return true;
else if (n == 1)
return false;
else
isEven(n - 2);
}
When running console.log(isEven(50)); it gives me an output of undefined. Of course the solution is to put a return in front of isEven(n - 2);
Why is that though, shouldn't the function either be returning true or false? How does n become undefined?
Because imagine that you call isEven(3), then isEven(3-1) is called inside of that function and it evaluates to false but you arent returning that value from isEven(3)
Your code, as written, will either:
return true
return false
recursively call itself and, eventually, return undefined because no return statement was triggered
If you want to do something with the value you get from calling the function recursively, then you need to write code to do that thing.
Hence the need to return
Say n = 3. You want your function to return false
There are three calls made to isEven. Each of those calls needs to return something to the thing that called it. From outermost call to innermost call they look like:
output "false" <- return isEven(3) <- return isEven(1) <- return false

Why this recursive javascript function returns undefined?

In the following recursive function, I expect the function to return "arrived" at the end but instead, it returns undefined. Isn't that when the excution goes in the if block the code should return? Appreciate your comments on this.
function myFun(i){
if(i===0){return ('arrived');}
i = i - 1;
myFun(i);
}
If I change the code as follows then it'll return "arrived" but still don't know why the above doesn't return "arrived".
function myFun(i){
if(i===0){return ('arrived');}
i = i - 1;
return myFun(i);
}
The first function does not return a value because all code paths must return a value. And after the first line, there is no return statement. It only returns a value when called with 0 as parameter.
Recursion is a functional heritage and so writing your program in a functional style will yield the best results.
This means avoiding things like
imperative style statements for, if, switch, etc that do not return a value
mutation or variable reassignments like i = i + 1
const myFun = i =>
i === 0
? "arrived"
: myFun (i - 1)
console.log (myFun (10))
// "arrived"
Notice expressions, unlike statements, evaluate to a value. We made the following changes
function statement function myFun (i) { ... } replaced with a function expression myFun (i) => ...
if statement replaced with ternary expression, eg condition ? ifTrue : ifFalse
variable assignment statement i = i - 1; myFun(i) replaced with expression myFun(i - 1)
Note, the return statement itself is a side effect and has little use in a functional JavaScript program.
Going along with the other answer here, all code paths must return a value! An advantage to writing your program in a functional style means you can't write a function that doesn't return a value, nor can you write a conditional with only one branch.
TL;DR: use functional style and your problem automatically vanishes

JavaScript - Meaning of this Higher Order Function

first of all sorry if I'm not posting on the right place or if there's already a duplicate, but i don't know what to call this or how to search for it.
Can someone please explain to me what does the following code mean:
function noisy(f) {
return function(arg) {
console.log("calling with", arg);
var val = f(arg);
console.log("called with", arg, "- got", val);
return val;
};
}
noisy(Boolean)(0);
// → calling with 0
// → called with 0 - got false
Why do I need to have (Boolean) after the function call ?
noisy(Boolean)(0);
What do i call this type of function call ?
Thanks in advance!
This is tricky stuff. (Boolean) might throw you off here, but really it's just a regular old parameter. You could replace Boolean with any function, like doStuff, and it'd still work.
And yes, as you pointed out, this is a duplicate question. You're looking at something called "closure." Here's a fantastic answer from StackOverflow:
How do JavaScript closures work?
"noisy" is a function that returns a function if you call it.
By passing Boolean into the function, Boolean is called like Boolean(0) which results in false since 0 is a falsy value.
Boolean is just a constructor that you can use to create booleans or to cast any value to a boolean.
You are calling a function noisy(...) which is returning another function which it constructs using information from its parameters. The function call noisy(Boolean)(0); is actually two function calls and could (maybe should) be written as:
var noisyFunction = noisy(Boolean)
noisyFunction(0)
The fact that noisy() takes a function (Boolean is a function MDN). Has no real effect on the syntax being used here, it could take no arguments, or something less zany.
Your selection of the higher-order-functions tag really kind of sums it up. This is an example of programming with them. The fact that the value f is available to noisyFunction after noisy returns is the result of a closure (MDN). Some programmers might then describe this as, "using a closure", but it is not specific to the pattern shown.
You need to pass an f - it could be anything else than the Boolean function. Try
const increment = x => x+1;
const noisyInc = noisy(increment);
console.log(noisyInc(1));
In your original code, the intermediate variable is omitted - just like I could've written noisy(increment)(1) here.

Fail to understand function behavior with/out closures in console.log

I am very new to JS.
I ran into something strange, while learning about console.log behavior. Console is very important for me, because I believe that if console.log does not see it, then it is not there. I will start with simple things, just to make sure I do not miss anything.
Assumption: console.log can print results of simple calculations.
console.log(1+0); //1. Console.log can calculate!
Assumption: console.log can print results of functions, if those return values.
var test = function(a,b){
var c = a+b;
return c;
};
console.log(test); //prints the assigned value of the variable "test", which happens to be a function and thus function code is printed. Function is NOT called here.
console.log(test()); //prints NaN, since the function is called but no arguments are provided. Thus, JS is unable to calculate the result.
console.log(test(1,1)); // this one prints the result of the function, which is variable "c"
console.log(test(1,1) + 2); //I can then manipulate results further in the console.
Assumption: with closures there is a problem?
var testClosure = function(a,b){
var c = a+b;
return function(){
var d = c + 1;
return d;
}
};
console.log(testClosure); //so far standard behavior - console prints the assigned value of a function - its code.
console.log(testClosure()); //trying to call the function here without arguments. Expected result that it will attempt to calculate "d" and return NaN (since it cannot calculate), but it returns the code for the anonymous function. JS does not attempt to do calculation.
console.log(testClosure(1,2)); //does not produce the expected result of 4. It produces same output as in the previous case. JS does not attempt to do calculation for some reason.
var result = testClosure(1,2);// Do I understand it correctly that at this point I only create a reference but testClosure() function is not actually launched? Therefore, variable "result" does not have any meaningful value yet?
console.log(result); //printing the assigned value of this variable, which is the code for the anonimous function in testClosure().
console.log(result()); // here I am actually calling the testClosure() function by proxy and get the desired result of 4.
My main questions are
Why does
console.log(test(1,1));
work and
console.log(testClosure(1,2));
does not?
Why does
console.log(testClosure(1,2));
does not work but
var result = testClosure(1,2);
console.log(result());
does work.
I seem to be doing essentually the same thing: calculate given the provided argument and print the result.
Where is the key difference I am missing, since I obviously do?
test is a function, which returns a value, but testClosure is a function which returns a function which returns a value. Function in JS is a first class object, which means that it also can be used as an argument, assigned to a variable or returned from a function (that's what you do in your closure example, you return a function, not the value). But to get a value of this returned function you have to call it too, it does not call itself.
console.log( typeof test(1,2) ); // number
console.log( typeof testClosure(1,2) ); // function, which also needs to be called
console.log( typeof testClosure(1,2)() ); // number
// ---------------------------------^-----// call the returned function
1) because you are logging the result of executing the function, which returns the expected value.
2) because you are logging the result, which in this case is a function, you need to then execute this function to get the desired value - try doing console.log(testClosure(1, 2)());

Do I have to return something in javascript function?

In JavaScript functions, do I need to return something (true or false) ? So far, all the functions I wrote without returning anything work just fine. I'm just curious.
No; Javascript functions are not required to return a value.
If you call a function that doesn't return a value, you'll get undefined as the return value.
no you dont. I believe if you do
var result = iAmADefinedFunctionThatDoesntReturnAnything();
result will be undefined.
Edit, this screenshot should be illuminating (forgive the mistake when i fail to invoke f):
No you don't
BUT
if you find yourself doing something like this
function myFun(){
if (1 == 2){
return true ;
}
}
Now you should know you are doing something wrong in your code because it doesn't make sense that only part of the function return a value

Categories

Resources