Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Array
  • JS String
  • JS Object
  • JS Operator
  • JS Date
  • JS Error
  • JS Projects
  • JS Set
  • JS Map
  • JS RegExp
  • JS Math
  • JS Number
  • JS Boolean
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter
Open In App
Next Article:
What is the (function() { } )() construct in JavaScript?
Next article icon

JavaScript Function() Constructor

Last Updated : 09 Jun, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

The JavaScript Function() constructor is used to create new function objects dynamically. By using the Function() constructor with the new operator, developers can define functions on the fly, passing the function body as a string. This allows for greater flexibility in situations where functions need to be created based on runtime conditions or user input.

One notable characteristic of functions created with the Function() constructor is that they have a global scope, meaning they are accessible from anywhere in the code.

Syntax:

var variable = new Function(arg1, arg2..., Function Body)

Parameters:

  • arg*: It is an optional parameter. A function can contain any number of string arguments.
  • Function Body: It is an argument that contains the Javascript statements containing the function definition.

Below are some examples that show the use of the Javascript function constructor.

Example 1: In this example, we will see the basic use of the Javascript function constructor.

HTML
<!DOCTYPE HTML> <html> <head>     <script type="text/javascript">         <!--         var func = new Function("x", "y", "return x*y;");         function geeks() {            var result;            result = func(10,20);            document.write ( result );         }     </script> </head>  <body>     <h1 style="color:green">         Geeks For Geeks     </h1>     <h3>Javascript function constructor</h3>     <p>Click the following button to see the result</p>      <input type="button" onclick="geeks()"value="Click Me">  </body> </html> 

Output:

Javascript function constructor
Javascript function constructor

Example 2: In this example, we will create a Javascript constructor and print the values of the function.

HTML
<!DOCTYPE HTML> <html> <head>     <script type="text/javascript">         <!--         var func = new Function("firstName", "lastName",                                  "return firstName + ' ' + lastName + ' ' + firstName;");         function geeks() {            var result;            result = func("Geeks","for");            document.write ( result );         }     </script> </head>  <body>     <h1 style="color:green">         Geeks For Geeks     </h1>     <h3>Javascript function constructor</h3>     <p>Click the following button to see the result</p>      <input type="button" onclick="geeks()"value="Click Me">  </body> </html> 

Output:

Javascript function constructor
Javascript function constructor

Conclusion

The JavaScript Function() constructor provides a dynamic way to create functions, offering flexibility in scenarios where functions must be generated at runtime. While powerful, it should be used with caution to avoid security and performance issues. Understanding how and when to use the Function() constructor can enhance your JavaScript programming skills, allowing you to create more adaptable and responsive applications. By leveraging this feature effectively, developers can write more dynamic code, making their applications more robust and versatile.

We have a complete list of Javascript Functions, to check those please go through this Javascript Function Complete reference article.


Next Article
What is the (function() { } )() construct in JavaScript?

A

amitsingh2730
Improve
Article Tags :
  • JavaScript
  • Web Technologies

Similar Reads

  • Default Constructor in JavaScript
    In JavaScript, a default constructor is not explicitly defined like in some other programming languages such as Java or C++. In JavaScript, objects can be created without a formal constructor. When you create an object using the new keyword along with a constructor function, that function serves as
    2 min read
  • JavaScript Generator() Constructor
    In JavaScript, there is no particular Generator() constructor but instead, we can use generator function declaration to construct a Generator object which is iterable as the Generator object is a subclass of the Iterable class. Generators are usually used to create functions that can be exited and r
    1 min read
  • What is the (function() { } )() construct in JavaScript?
    If you've ever played around with JavaScript, you might have seen this expression. It's like a strange set of symbols, but it has a special name that is an immediately invoked function expression, or IIFE. In this article, we will understand each element of the expression as well as the functionalit
    3 min read
  • What is a Constructor in JavaScript?
    A constructor in JavaScript is a special function that is used to create and initialize objects. When we want to create multiple objects with similar properties and methods, the constructor is used as a blueprint to create similar objects. This is useful when you want to create multiple objects with
    8 min read
  • JavaScript Anonymous Functions
    An anonymous function is simply a function that does not have a name. Unlike named functions, which are declared with a name for easy reference, anonymous functions are usually created for specific tasks and are often assigned to variables or used as arguments for other functions. In JavaScript, you
    3 min read
  • JavaScript Function Definitions
    JavaScript functions are declared using the function keyword, either as a declaration or expression. Declarations define named functions, while expressions assign functions to variables. Both enable code reuse and modularity. Syntax Function Declarations function functionName( parameters ) { // Stat
    3 min read
  • JavaScript Symbol() Constructor
    The Symbol() constructor is used to create a new symbol. The Symbol() constructor returns a value of the type of symbol with static properties. Every time we call the constructor a unique symbol is created. A Symbol constructor is a primitive data type having no object or no methods which are genera
    2 min read
  • JavaScript Constructor Method
    A constructor in JavaScript is a special function used to create and initialize objects. It sets up object properties and is typically invoked using the new keyword. Constructors allow for the creation of multiple instances with similar properties and methods. In JavaScript, constructors can be defi
    8 min read
  • JavaScript String() Constructor
    The JavaScript String() Constructor is used to can be used as a constructor or a function. that creates a new string object. It can be used in two different ways: Syntax:Invoked with the new keyword: new String(object);Invoked without the new keyword: String(object);Parameters: This constructor acce
    3 min read
  • JavaScript Number() Constructor
    Javascript Number() Constructor is used to create a new number object but, if we call it as a function on another data type it will perform type conversion to number if possible. Syntax: Number(object) Parameters: This function accepts a single parameter as mentioned above and described below: objec
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences