Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 8 years ago.
Improve this question
What is return in JavaScript ? And what is advantage of using return function ? I can also get 16 by doing this --
var number = function ( ok ){
confirm( 8 * ok );
}
number(2);
______________________…
So, What is the advantage of using return function ?
var timesTwo = function(number) {
return number * 2;
};
var newNumber = timesTwo (8);
confirm(newNumber);
BTW, is return used for Ex :---->
var timesTwo = function(number) {
return number * 2;
};
var newNumber = timesTwo (8);
if ( newNumber === 16 ){
confirm("success");
}
else{
confirm("failure");
}
Am i right ? because i think only function can't be used for If-Else or any other code,so return used ??
return is used so that a function can return a value to its caller. If return is not used like this, then the programmer has to use global variables to pass a computed value from a function to its caller, which is bad. Also, return is not a function.
I hope this clears out the air for you about return.
Now, about your example. You've written -
var number = function ( ok ){
confirm( 8 * ok );
}
number(2);
In the first line, you are declaring an unnamed function, and you are assigning a reference to it to the number variable. If any variable holds a reference to a function, then the function can be called by placing two first brackets after the variable. That's what you are doing at the last line.
About the second example -
var timesTwo = function(number) {
return number * 2;
};
var newNumber = timesTwo (8);
confirm(newNumber);
Here you are again creating an unnamed function and storing its reference to timesTwo. This function now returns a result, so when you call it with 8, the computed value 16 gets returned by the function and is assigned to newNumber.
About the last one -
var timesTwo = function(number) {
return number * 2;
};
var newNumber = timesTwo (8);
if ( newNumber === 16 ) {
confirm("success");
}
else {
confirm("failure");
}
You could also rewrite it as follows -
var timesTwo = function(number) {
return number * 2;
};
if ( timesTwo(8) === 16 ) {
confirm("success");
}
else {
confirm("failure");
}
Here, rather than storing the returned value in newNumber and checking its value, you are directly calling the function, whose returned value will then be checked with 16. This is another benefit that returns provide - a function's returned value can be used directly in an if condition check, without storing it first in a variable.
Functions can be used in if statements. Refer to this question:
Using function's return value in if statement
Related
Below is a module that takes one argument, a number, and then either adds or subtracts a const, magicNumber, from it depending on whether or not the number is even or odd, respectively. When I run this code, however, I simply get "undefined." What am I doing wrong?
module.exports = (number) => {
let answer; //Answer is declared in the global scope
const magicNumber = 5; //magicNumber is declared in the global scope
if (number % 2) { //If the number is even
add(number); //run the number through the add function
} else { //otherwise run the number through the subtract function
subtract(number);
}
function add(number){ //Function takes the number as argument, does the math, and returns the value of answer.
answer = number + magicNumber;
return answer;
}
function subtract(number){ //Function takes the number as argument, does the math, and returns the value of answer.
answer = number - magicNumber;
return answer;
}
};
Your exported block is not returning anything hence it’s undefined by default.
module.exports = (number) => {
let answer; //Answer is declared in the global scope
const magicNumber = 5; //magicNumber is declared in the global scope
if (number % 2) { //If the number is even
return add(number); //you should return here as well
} else { //otherwise run the number through the subtract function
return subtract(number);//you should return here as well
}
function add(number){ //Function takes the number as argument, does the math, and returns the value of answer.
answer = number + magicNumber;
return answer;
}
function subtract(number){ //Function takes the number as argument, does the math, and returns the value of answer.
answer = number - magicNumber;
return answer;
}
};
function makeMultiplier(multiplier) {
var myFunc = function (x) {
return multiplier * x;
};
return myFunc;
}
var multiplyBy3 = makeMultiplier(3);
console.log(multiplyBy3(10));
So I got this example from an online course, the console prints: 30
I don't exactly understand how the value 30 was obtained, below is what I think is how it is executed, but please do correct me if false.
I assume first that the value of multiplier becomes 3, then the function makeMultiplier returns 3 * X.
From here, by assigning var multiplyBy3 = makeMultiplier(3), essentially multiplyBy3 is now a function that returns 3 * X.
Therefore when 10 is plugged in, it returns 3 * 10 = 30.
Yes, you are correct, remember that functions can be passed around to and from variables and other functions.
makeMultiplier returns a reference to a function closure, it doesn't execute it yet.
var multiplyBy3 = makeMultiplier(3); Puts the value 3 into the closure function, and returns a reference to it (still doesn't execute it yet).
At this stage we have:
function multiplyBy3(x) {
return 3 * x;
}
console.log(multiplyBy3(10));
multiplyBy3(10) calls the reference to the closure function and passes in 10.
The example you posted is also referred to as "currying". Here's another javascript example of currying.
I do recommend that you get in the habit of using ES6 syntax. Your example rewritten in ES6:
const makeMultiplier = multiplier => x => multiplier * x;
const multiplyBy3 = makeMultiplier(3);
console.log( multiplyBy3(10) ); // 30
or
console.log( makeMultiplier(3)(10) ); //30
Correct. This is what is known as a 'closure' (a function that returns another function that has access to the scope of the parent function.
Hi I am confused with this Javascript function:
var currying = function(a) {
return function(b){
return function(c){
return function(d){
return a + b /c * d;
};
};
};
};
var a = currying(4)(8);
var b = a(2)(6);
console.log(b);
It outputs 28 but I am not sure how did Javascript evaluated the function. I also have learned that a = 4, b = 8, c = 2 and lastly d = 6. Thank you for somebody that will be able to explain the function.
When you use currying you are writing a function that takes one argument, that will return a function taking the next argument until all arguments are supplied.
In this case you need to call the returned function 4 times until you get to the last function and evaluate all the arguments.
This is good because you can pass in arguments at different times during the execution of your code and you can create new functions with arguments already set within the closure of the final functions. eg.
const fourPlusTwo = currying(4)(2)
now you can use the new function fourPlusTwo anywhere in your code and you will have those arguments baked in the closure of the remaining two functions.
The code you have is a non standard example but maybe if you needed to calculate tax throughout your app you could do something like.
const inclusiveTax = rate => amount => {
return '$' + (amount * (rate / (100 + rate))).toFixed(2)
}
const norwayIncomeTax = inclusiveTax(60.2)
const strayaIncomeTax = inclusiveTax(32.5)
const muricaIncomeTax = inclusiveTax(31.5)
console.log(
norwayIncomeTax(50000),
strayaIncomeTax(50000),
muricaIncomeTax(50000)
)
Using just one function you have curried the tax rate for 3 separate countries and returned functions waiting for the amount.
You should know the difference between function object and function call.
like: var a = function(v){return v + 1;} a is a function object. Then a(2) invokes function a.
Try to understand the procedure step by step.
currying is a function which return another function.
so currying(4) returns a function(a is given value 4):
function(b){
return function(c){
return function(d){
return 4 + b /c * d;
};
};
};
};
then currying(4)(8) also is 'var a' returns another function:
function(c){
return function(d){
return 4 + 8 /c * d;
};
};
};
invoking a(2) returns a function object:
function(d){
return 4 + 8 / 2 * d;
};
};
finally a(2)(6) returns 4 + 8 / 2 * 6 which is 28.
This is kind of lexical scoping called Closures
Basically: A closure is a function within function that has access to all parent's variables and parameters. As every parameter in javascript is by default passed by reference, it can even modify parent's variables so you can later execute parent function to see the changes. The great example is jquery's ready function that wraps all other functions within.
You can read more about this here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures
This is a very convoluted example of currying - hence the name of the main function.
Currying originates in the field of functional programming and to fully understand it I would suggest that you do some reading, especially as it is implemented in javascript.
To give you some pointers:
In the line:
var a = currying(4)(8);
the first function is called with a parameter of 4; the result of that function call is another function which is then called immediately with a parameter of 8.
Ultimately, all that happens is that the line:
return a + b / c * d;
is executed with the values 4, 8, 2 and 6 for each of the respective variables.
Normal arithmetic rules are applied to give you an answer of 28 (divide first, then multiply and finally add).
The working javascript snippet below does not include validation as it is only being used for learning purposes. However, I am not understanding the flow of events after variable 'isBetween' is defined within the buildBoundDetector() function. Why does passing a number through variable 'f' work?
function buildBoundDetector( lowerBound, upperBound ) {
var isBetween = function(number){
if(lowerBound <= number && number <= upperBound){
return true;
}
return false;
}
return isBetween;
}
var f = buildBoundDetector( 1, 100 );
f(45);
buildBoundDetector() is a function that returns a function. In Javascript, you can assign a function to a variable. That's what buildBoundDetector() does. It defines an anonymous function, then assigns it to isBetween, then returns isBetween. f is set to the result of buildBoundDetector(), which is that function. Because f is a function, you can call it.
In JavaScript, and many other languages, functions can be treated as values. So your first function returns a value which itself is a reference to a function. Then, the returned function value is applied, like any other function, to the argument 45.
I have recently encountered a nasty issue in JS.
Let say we pass a map, an array of objects to a function f.
var o=[{a:0}];
function f(a){
for(var i in a){
if (a.hasOwnProperty(i)){
a[i]=null;
}
}
return a;
};
var outp=f(o);
alert(outp[0]+" === "+o[0]+" : "+(outp[0]===o[0]));
// here we expect loose equality, and equality in type,
//furthermore it should identically equal as well, and we got right!
But, we can not pass total responsibility of an object to a function as argument, same like in functional paradigm o=(function(o){return o})(), because any kind of modification to o is not referenced!
var o=[];
function ff(a){
return (a=undefined);
};
var outp=ff(o);
alert(outp+" === "+o.constructor+" : "+(outp===o));
// here we expect true, but we got false!
Why is the above described reference loss and
presumably different referencce handling in the second use case,
though in both case, functions got the array argument in the 0. position?
Javascript always passes arguments by value, so this won't work:
function foo(x) {
x = 100;
}
y = 5
foo(y)
y == 100 // nope
However this does work:
function foo(x) {
x.bar = 100;
}
y = {}
foo(y)
y.bar == 100 // yes
In the second snippet x is still passed by value, but this very value is a reference (pointer) to an object. So it's possible in a function to dereference it and access what's "inside" the object.