0

I am sure that this has been asked and answered before, but I can't seem to find the right terminology to find an answer. I need to dynamically create a series of functions for later use which use certain values defined by parameters upon creation. For example:

var i = "bar";

var addBar = function(x) {
    // needs to always return x + " " + "bar"
  return x + " " + i;
}

i = "baz";

var addBaz = function(x) {
    // needs to always return x + " " + "baz"
  return x + " " + i;
}

alert(addBar("foo")); // returns "foo baz" because i = "baz"

Is there a way I can pass i to these functions so that the original value is used, and not the reference to the variable? Thank you!

TobyRush
  • 654
  • 4
  • 20
  • 1
    I can think of three solutions: 1. Use two separate variables (`const`, actually): `i` and, say, `j`. 2) Just write the values inline, e.g. `return 'foo ' + i;` 3) Use [currying](https://stackoverflow.com/questions/36314/what-is-currying). – kmoser Dec 27 '21 at 19:00
  • Thanks! The first two options aren't possible in my actual situation, but it sounds like currying — if I understand it correctly — is just what I'm looking for. – TobyRush Dec 27 '21 at 19:12

1 Answers1

3

You would have to do something that stores the variable. Making a function that returns a function is one way to do it.

var i = "bar";

var addBar = (function (i) { 
  return function(x) {
    return x + " " + i;
  }
}(i));

i = "baz";

var addBaz = (function (i) { 
  return function(x) {
    return x + " " + i;
  }
}(i));

console.log(addBar("foo")); 
console.log(addBaz("foo")); 
epascarello
  • 204,599
  • 20
  • 195
  • 236