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: 8In above example,
- We use the
Functionconstructor to create a new function object namedaddFunction. - We call the
addFunctionlike any other function, passing in the values fornum1andnum2. The result (8) is stored in theresultvariable.
Challenge
EasyYour 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
1Course Introduction
What you will learn?3Ways of Function Declaration
Basic FunctionNested FunctionReturning a FunctionFunction ExpressionsArrow FunctionFunction Constructor