Web

November 14, 2019

Create functions from strings in Javascript

There are a few ways to declare functions in Javascript. Below are some common examples.

1
2
3
4
5
6
7
8
9
10
11
12
13
var sum = function (a, b) {
  return a+b
}

// Arrow function
var sum = (a, b) => { return a+b }

// Inside a class
class Math {
  sum(a, b) {
    return a+b
  }
}

A lesser known way of declaring a function is with the Function constructor. It works like this. You call the Function class with the new keyword. The first arguments are the parameter names and the last argument is the code.

1
2
var sum = new Function('a', 'b', 'return a+b');
console.log(sum(1,2)) // prints 3

This means that now we can create functions from strings and the code can be constructed from variables.

The use case

Suppose we wanted to create functions for addition, subtraction, multiplication and division. We could declare them all like this.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
const addition = function(a, b) {
  return a+b
}

const subtraction = function(a, b) {
  return a-b
}

const multiplication = function(a, b) {
  return a*b;
}

const division = function(a, b) {
  return a/b;
}

There is a lot of code duplication here which we can fix with the Function constructor.

1
2
3
4
5
const operators = [ 'addition', 'subtraction', 'multiplication', 'division' ]
const symbols = [ '+', '-', '*', '/' ]
var functions = operators.map((value, index) => {
  return new Function('a, b', 'return a' + symbols[index] + 'b;')
})

In this case we return an array with the function. If instead you’d want to declare them as global function we can do the following. Declare a global function like this.

1
2
window['variableName'] = "Hello there!"
console.log(variableName) // Hello there

Combining the above, we can do

1
2
3
4
5
const operators = [ 'addition', 'subtraction', 'multiplication', 'division' ]
const symbols = [ '+', '-', '*', '/' ]
operators.forEach((value, index) => {
  window[value] = new Function('a, b', 'return a' + symbols[index] + 'b;')
})

Conclusion

The use cases from the Function constructor are not many. It is definitely not something that should be used often. If you need to create multiple functions, like in this example, you should first ask yourself if there is a way to accomplish the same result with introducing a new function parameter instead.

Reference to blog by Dmitri: 6 Ways to Declare JavaScript Functions

Reference to Mozilla docs: MDN web docs

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *