Sean
Sean

Reputation: 981

passing argument in high order function javascript

function doSomething(numbers, doIt){
  numbers.forEach(doIt(number));
}

var result = [];
var arr = [1,2,3,4];
doSomething(arr, function(num){
 result.push(num);
})

console.log(result);

Hi,

Why am I getting an error of "number is not defined" from above code? number should be each elements in arr, why is it not defined?

Thanks.

Upvotes: 0

Views: 47

Answers (6)

Hemant Metalia
Hemant Metalia

Reputation: 30678

In your function check spelling of number while calling doIt the number variable isnt available anywhere so it throws an error.

If you want doIt as callback, you just call it as numbers.forEach(doIt);

Upvotes: 0

Chad
Chad

Reputation: 2289

You would need to either pass a closure to forEach to capture the number variable to pass to doIt or just pass doIt as the forEach callback without calling it.

Capture option:

function doSomething(numbers, doIt){ 
  numbers.forEach(function (number) { 
    doIt(number); 
  }); 
} 
var result = []; 
var arr = [1,2,3,4]; 
doSomething(arr, function(num){ 
  result.push(num); 
}); 

console.log(result);

Pass as callback option:

function doSomething(numbers, doIt){ 
  numbers.forEach(doIt); 
} 
var result = []; 
var arr = [1,2,3,4]; 
doSomething(arr, function(num){ 
  result.push(num); 
}); 

console.log(result);

Upvotes: 0

Thalaivar
Thalaivar

Reputation: 23642

function doSomething(numbers, doIt){
  numbers.forEach(doIt);
}

var result = [];
var arr = [1,2,3,4];
doSomething(arr, function(num){
 result.push(num);
})

console.log(result);

Use this instead, as you are already iterating the numbers array and passing the function as second argument which would carry out num => each item in numbers array.

Upvotes: 0

isvforall
isvforall

Reputation: 8926

Your function doSomething needs to be like this

function doSomething(numbers, doIt) {
    numbers.forEach(doIt); // here you pass the function
}

Upvotes: 1

lesssugar
lesssugar

Reputation: 16181

You're passing an undefined argument to the doIt function.

Change that:

numbers.forEach(doIt(number));

to this:

numbers.forEach(doIt);

Fiddle

Upvotes: 0

deceze
deceze

Reputation: 522412

doIt(number) executes the function doIt, passing the variable number. That variable obviously doesn't exist anywhere at the time of calling.

What you actually want is to pass doIt as callback to forEach, and let forEach execute the function, passing it a number. To do that, you just need:

function doSomething(numbers, doIt){
  numbers.forEach(doIt);
}

Upvotes: 0

Related Questions