0

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?

Web_Designer
75.1k93 gold badges211 silver badges268 bronze badges
asked Apr 15, 2017 at 0:40
2

2 Answers 2

1

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; }
answered Apr 15, 2017 at 0:48
Sign up to request clarification or add additional context in comments.

Comments

0

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; };
answered Apr 15, 2017 at 0:57

1 Comment

Thanks for the explanation! It makes sense now:D

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.