0

var products  ['product1', 'product2', 'product3']

var color = 'blue';

function callback (product) {
   console.log(product + color)
}

function printEachProduct (products, color) {
   products.forEach(callback)

}

How can I have access to color param if my callback is defined outside of parent scope?

asotos
  • 327
  • 3
  • 14

2 Answers2

3
  1. callback must accept color as argument.
  2. Pass a new function to forEach that calls callback with the right arguments.
var products  ['product1', 'product2', 'product3']

var color = 'blue';

function callback (product, color) {
   console.log(product + color)
}

function printEachProduct (products, color) {
   products.forEach(function(product) { callback(product, color); })

}

I assume this is just the beginning of your code because as it is there is no reason for callback to exist.

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
  • i'm using es5 only. I used this just as an example. I just want to define for each callback outside of parent function as a standard, instead of using keword 'function' and calling callback inside of it – asotos Mar 26 '20 at 13:39
  • Then you are out of luck. Note that the answer you accepted does the same thing as mine, the parts are just placed a bit differently. – Felix Kling Mar 26 '20 at 14:56
  • @FelixKling Almost the same thing. With the difference being that you pass `color` and `product` to `callback` for each `product` in `products`. Whereas the curried solution only passes `color` once to `createCallback`, then passes only `product` to the resulting function for each `product` in `products`. – 3limin4t0r Mar 26 '20 at 17:29
1

You could use currying, and pass the color as first argument.

var products = ['product1', 'product2', 'product3'];

var color = 'blue';

function createCallback(color) {
   return function (product) {
      console.log(product + color);
   };
}

function printEachProduct(products, color) {
   products.forEach(createCallback(color));
}
3limin4t0r
  • 19,353
  • 2
  • 31
  • 52