Can someone explain to me how this function works? - javascript

I'm learning to code and I'm trying to understand Higher Order Functions and abstractions. I don't understand how this piece of code runs to return "true".
function greaterThan(n) {
return function(m) { return m > n; };
}
var greaterThan10 = greaterThan(10);
console.log(greaterThan10(11));
Thanks for the help.

The function greaterThan returns a function when called. The returned function has access to all the members of the outer function even after the function has returned. This is called closure.
function greaterThan(n) {
return function (m) {
return m > n;
};
}
When following statement is executed
var greaterThan10 = greaterThan(10);
it is converted as
var greaterThan10 = function (m) {
return m > 10;
};
So, greaterThan10 is now the function and can be called as
console.log(greaterThan10(11));
Now, value of m is 11 and return 11 > 10; returns as true.
Read more about closures:
How do JavaScript closures work?
Also, I'll recommend following great article to all the JS developers
http://dmitryfrank.com/articles/js_closures

Related

Anyone can me an explanation why this Javascript function cannot give desired result?

function person1(name) {
var n = name;
return (function (n) {
alert(n);
})(n);
}
person1('susan')();
person1('peter')();
The second statement cannot be run, anyone can give me a correct explanation.
person1('susan') does not return a function, it returns undefined, so you can't call it afterwards - the extra () results in the script throwing.
If you want calling person1 to return a function that, when called, alerts the name, remove the n parameter, and return a function that alerts name - but don't call the function, just return it, so the returned function can be called outside:
function person1(name) {
return () => {
console.log(name);
};
}
person1('susan')();
person1('peter')();
The code of your function is basically ok but the call person1 is not. You should omit the brackets after the call. Because your not returning a function back from person1. Actually you don't have a return value at all.
function person1(name) {
var n = name;
return (function (n) {
alert(n);
})(n);
}
person1('susan');
person1('peter');
This would work but can be simplified.

Currying function work in javascript

Can someone please explain the below 'Currying' function. When I set a break point, I can see values 'b' and 'c' are undefined and returned. But how does the system get the value 7 for 'b' and 9 for 'c' in this case. Its printing the correct result for 5*7*9, ie 315 in console.
function multiply(a){
return function (b){
return function (c) {
return a*b*c ;
}
}
}
var answer = multiply(5)(7)(9);
console.log(answer);
When you call multiply(5) a function is returned and that function is immediately called with multiply(5)(7) and have access to a and b, then a new function is returned and is also immediately called when multiply(5)(7)(9) and has access to a, b, and c.
The answer to why the nested functions have access to parent function parameters is closures. Please check this other question/answers about closures in javascript: link.
You can understand currying if you assign each intermediate result to a variable. Rewrite the function calls like this:
var x = multiply(5)
var y = x(7);
var answer = y(9);
Now it is more clear that the result of calling multiply(5) is a function. We call it with x(7) which passes the value of 7 to b. This results in another function which we call with y(9) which in turn passes the value of 9 to c and returns the final result.
When you call the multiply function, the important thing is each function returns an anonymous function. It will be easier if you give them names.
function multiplyA(a){
return function multiplyB(b){
return function multiplyC(c) {
return a*b*c ;
}
}
}
// When you call multiplyA(5)(7)(9)
// From the first, multiplyA(5) returns multiplyB with scope with multiplyA
// just like below
const a = 5;
const multiplyB = function(b){
return function multiplyC(c) {
return a*b*c ;
}
}
// Once more call multiplyB(7)
// It also returns function named multiplyC
const a = 5;
const b = 7;
const multiplyC = function(c) {
return a * b * c;
}
// Finally call mulitplyC(9) means 5 * 7 * 9
To understand it, closure and function scope will be helpful.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures

Calling a function by variable

I recently started to learn javascript by myself and I am reading a book called "Eloquent JavaScript". The following code is a sample script in the book which confused me:
function greaterThan(n) {
return function(m) { return m > n; };
}
var greaterThan10 = greaterThan(10);
console.log(greaterThan10(11));
Can someone please explain the logic of the last two lines? Does the greaterThan10 contain a truth value or it is a function?
You define greaterThan10 on the second to last line:
var greaterThan10 = greaterThan(10);
Whatever the greaterThan function returns in this case is what greaterThan10 will evaluate to.
On line 2 we see that greaterThan will return the following function expression:
function(m) { return m > n; }
After replacing the variable n with the value you passed we get this:
function(m) { return m > 10; }
It can look a little confusing at first, but just keep in mind that functions are objects in JavaScript.
greaterThan(n) is a function that returns an anonymous function with the definition:
function(m) { return m > n; }
Therefore, when we call greaterThan(10) we expect it to return an object that is in fact a function:
function(m) { return m > 10; }
Later on we just assign that object/function to a variable, and call it like we would call any function.
In short, just imagine that we had:
var greaterThan10 = function(m) { return m > 10; };

Can you explain return in javascript?

How is return used in javascript ?
var makeNoise = function() {
console.log("Pling!");
};
makeNoise();
// → Pling!
var power = function(base, exponent) {
var result = 1;
for (var count = 0; count < exponent; count++)
result *= base;
return result;
};
console.log(power(2, 10));
// → 1024
I am learning about functions in chapter 3 in eloquent javascript.
This is possible the best description ever. The return statement ends function execution and specifies a value to be returned to the function caller.
Read from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/return
And I would recommend you visit www.codecademy.com they will help you learn faster and understand concepts easily
When a function is invoked, it begins execution with the first statement and ends when it hits the } that closes the function body. That causes the function to return control to the part of the program that invoked the function.
The return statement can be used to cause the function to return early. When return is executed, the function returns immediately without executing the remaining statements.

Runtime error when executing simple closure in Javascript

Im new to JS and trying to learn. The spec requires the following:
Write a function that takes another function* as an argument and creates a version of the function that can only be called one time. Repeated calls to the modified function will have no effect, returning the value from the original call. How could you do this without using a closure? Is it even possible? How could you do this with a closure? *Note: This original input function should not have any parameters.
This is what I have:
var divide = function () {
var x = 2;
var y = 6;
return y/x;
}
var mainFunc = function (func) {
return func(){
return y/x + 1;
}
}
var output = mainFunc(divide);
console.log(divide());
console.log(output());
console.log(output());
I'm getting an "Unexpected token{" error at "return func(){" I don't quite understand what i'm doing wrong? Per the spec, I am passing divide() to mainFunc() and setting it to a reference variable output. I then call the divide() and output() multiple times to test if the closure works and that modified function only happens once. What am I missing or not understanding?
Thanks for the help.
Here you go:
function runonce(func) {
return (function(func) {
var ran = false;
var retval;
return function() {
if (!ran) {
ran = true;
retval = func();
}
return retval;
}
})(func);
}
function realfunction() {
console.log('really running');
return 5;
}
var realfunctionrunner = runonce(realfunction);
realfunctionrunner();
realfunctionrunner();
realfunctionrunner();
Study the code, the whole trick is a "self contained library" which result is returned from the runonce function

Categories

Resources