Menu
Coddy logo textTech

Function Constructor

Lesson 11 of 14 in Coddy's Function Declarations in JavaScript course.

The Function constructor is a built-in function in JavaScript that allows you to create new function objects. It takes arguments representing the function's parameters, function body code as a string, and (optionally) an optional string specifying the function's "this" value within the function.

Imagine you need to construct a function on the fly based on certain conditions or user input. The function constructor gives you that flexibility, but it can be less readable and more error-prone compared to traditional function declarations or expressions.

// Function constructor creating a simple addition function
const addFunction = new Function("num1", "num2", "return num1 + num2;");

// Calling the dynamically created function
const result = addFunction(5, 3);
console.log(result); // Output: 8

In above example,

  • We use the Function constructor to create a new function object named addFunction.
  • We call the addFunction like any other function, passing in the values for num1 and num2. The result (8) is stored in the result variable.
challenge icon

Challenge

Easy

Your task is to write JavaScript code to create Function constructor named calculateCube which calculates the cube of a number using the function constructor.

Try it yourself

// Write code here

All lessons in Function Declarations in JavaScript