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:
How to Store a JavaScript Fnction in JSON?
Next article icon

How to transform String into a function in JavaScript ?

Last Updated : 26 Jun, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

In this article, we will see how to transform a String into a function in JavaScript. There are two ways to transform a String into a function in JavaScript. The first and easy one is eval() but it is not a secure method as it can run inside your application without permission hence more prone to third-party attacks. The second one is Function() which is way more secure than eval().

  • Javascript eval(): This method takes a string as an argument and converts it into a function. Here the string can be a JavaScript expression, variable, statement, or sequence of statements.
  • Function constructor: Functions created with the Function constructor do not create closures to their creation contexts; they are always created in the global scope. They will only be able to access their own local and global variables when they execute, not variables from the scope in which the Function constructor was created.

Example 1: The following code example shows another way to use Function Constructor to convert the string to function.

HTML




<!DOCTYPE html>
<html>
  
<body>
    <h1 style="color:green">
        GeeksforGeeks
    </h1>
      
    <h3>
        This example shows how we can transform string
        into a function in javascript using Function
        Constructor
    </h3>
  
    <p> The code output is :
        <span id="result"></span>
    </p>
  
    <script>
        var fnstring = "func";
        var fnparams = ["first", "second", "third"];
  
        // find an object
        var fn = window[fnstring];
  
        // check if object a function?
        if (typeof fn === "function") {
            fn.apply(null, fnparams);
        }
  
        function func(a, b, c) {
            document.getElementById("result").innerHTML = b;
        }
    </script>
</body>
  
</html>
 
 

Output:

 

Example 2: The below code example demonstrate different ways to convert a string into a function.

HTML




<!DOCTYPE html>
<html>
  
<body>
    <h1 style="color:green;">
        GeeksforGeeks
    </h1>
      
    <h3>
        This example shows how we can transform string
        into a function in javascript
    </h3>
    <h3>1. Use of eval()</h3>
  
    <p>
        When string "var func = function(){ return a+b }" is
        passed in eval() and func() is called, The output is :
        <span id="result"></span>
    </p>
  
    <h3>2. Use of Function constructor</h3>
  
    <p>
        When strings "x=5", "y=20", "return x*y" is
        passed in Function constructor and fn() is called,
        The output is :
        <span id="func1"></span>
    </p>
  
    <p>
        When strings "x=5", "y=20", "return x*y" is
        passed in Function constructor and fn(4,10) is called,
        The output is :
        <span id="func2"></span>
    </p>
  
    <script>
        // use of eval()    
        var a = 100;
        var b = 200;
        eval("var func = function(){ return a+b }");
        document.getElementById("result").innerHTML = func();
        // Use of Function Constructor
        const fn = new Function("x=5", "y=20", "return x*y");
        document.getElementById("func1").innerHTML = fn();
        document.getElementById("func2").innerHTML = fn(4, 10);
    </script>
</body>
  
</html>
 
 

Output: The output shows the transformation of a string into a function.

 



Next Article
How to Store a JavaScript Fnction in JSON?

C

chiragchouhan163
Improve
Article Tags :
  • HTML
  • JavaScript
  • Web Technologies
  • HTML-Questions
  • JavaScript-Questions

Similar Reads

  • How to Store a JavaScript Fnction in JSON?
    In JavaScript, we can store JavaScript functions in JSON objects, allowing us to serialize and store executable code alongside data. we will explore three approaches to store a JavaScript function in JSON. These are the following approaches: Table of Content Using JSON.stringify()Using a Custom toJS
    2 min read
  • How to execute a function when its name as a string in JavaScript ?
    To execute a function when its name is a string in JavaScript, we have multiple approaches. In this article, we are going to learn how to execute a function when its name is a string in JavaScript. Example: function myFunction() { ...}const functionName ="myFunction";Below are the approaches used to
    3 min read
  • How to write a function in JavaScript ?
    JavaScript functions serve as reusable blocks of code that can be called from anywhere within your application. They eliminate the need to repeat the same code, promoting code reusability and modularity. By breaking down a large program into smaller, manageable functions, programmers can enhance cod
    4 min read
  • How to convert string into float in JavaScript?
    In this article, we will convert a string into a float in Javascript. We can convert a string into a float in JavaScript by using some methods which are described below: Methods to Concert String into Float:Table of Content Method 1: By using Type Conversion of JavaScriptMethod 2: By using parseFloa
    6 min read
  • How to create a function from a string in JavaScript ?
    The task is to create a function from the string given in the format of the function. Here are a few approaches that are listed below: Using Function() ConstructorUsing eval() MethodApproach 1: Using Function() ConstructorUse the Function() Constructor to create a function from the string.It accepts
    2 min read
  • How to convert string of any base to an integer in JavaScript ?
    Given a string containing an integer value and along with that user passes a base value. We need to convert that string of any base value to an integer in JavaScript. String Integer "1002" 1002 For performing the above-illustrated task, we would be using a method (or a function) provided by JavaScri
    3 min read
  • How to Convert String to JSON in JavaScript?
    In JavaScript, converting a string to JSON is important for handling data interchangeably between server and client, parsing external API responses, and storing structured data in applications. Below are the approaches to converting string to JSON in JavaScript: Table of Content Using JSON.parse()Us
    2 min read
  • How to Convert JSON to string in JavaScript ?
    In this article, we are going to learn the conversion of JSON to string in JavaScript. Converting JSON to a string in JavaScript means serializing a JavaScript object or data structure represented in JSON format into a textual JSON string for data storage or transmission. Several methods can be used
    3 min read
  • How to Convert String to Camel Case in JavaScript?
    We will be given a string and we have to convert it into the camel case. In this case, the first character of the string is converted into lowercase, and other characters after space will be converted into uppercase characters. These camel case strings are used in creating a variable that has meanin
    4 min read
  • How a Function Returns an Object in JavaScript ?
    JavaScript Functions are versatile constructs that can return various values, including objects. Returning objects from functions is a common practice, especially when you want to encapsulate data and behavior into a single entity. In this article, we will see how a function returns an object in Jav
    3 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