0

I am having a little bit of trouble understanding Higher Order Functions in javascript.

Can someone explain to me the difference of what's going on in these two situations?

Scenario 1:

// A function that takes in a number (x) and adds one to it. 
function doMath(x){
  return function (x){
    return x + 1;
  }
}

var didMath = doMath(5);
console.log(didMath()); // returns error

var didMath = doMath();
console.log(didMath(5)); // returns 6

var didMath = doMath(100);
console.log(didMath(5)); // still returns 6

Scenario 2:

function doMath2(x,callback){
  return callback(x);
}

function add(x){
  return x + 1;
}

console.log(doMath2(5,add)); // returns 6, works perfectly fine

I was under the impression that closures have access to parameters from their containing functions. Why is it that in Scenario 1, the "x" param in doMath is not accessible by the contained function?

2 Answers 2

1

what is happening here is you are never storing the value of x, you always return a new function, see this example it should work as you expect and maybe helps you to undersant

function doMath(x){
var y = x;
    return function(y){
        return y + 1;
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, this makes sense, in combination with Mathieu's answer.
1

In scenario 1 The first one outputs an error because the returned function expects an argument and you don't give one. If you remove the argument it works:

// A function that takes in a number (x) and adds one to it. 
function doMath(x){
  return function (){ // <--- here
    return x + 1;
  }
}

var didMath = doMath(5);
console.log(didMath()); 

In your two other examples you do give an argument and that is the one taken into account. Not the value that you give as parameter to doMath()

Comments

Your Answer

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.