Changing a function into a string and reversing the process in JavaScript

// Just an interesting point to note: The same outcome occurs when utilizing the full syntax as shown below.
const a = () => {
  return "hello world"
}
const stringifiedA = a.toString()
const b = new Function(stringifiedA)
console.log(b());  // undefined

Therefore, b serves as a closure of a, and there doesn't seem to be a way to prevent this wrapping. Has anyone discovered how to obtain the function without creating a closure?

Answer №1

New Function requires a function body as input, which is clearly explained on the mdn website:

The function definition should be a string containing JavaScript statements.

It's important to note that the parameters for the function are not included in this string and need to be passed separately.

There are multiple approaches to achieving this functionality:

  1. You can utilize eval, but if that's not an option (as mentioned in your question), consider the alternative approach:

const a = () => {
  return "hello world"
}
const aString = a.toString()
const b = eval(aString)
console.log(b());  // "hello world"

Please be cautious: similar to using New Function, when dealing with a stringified function that isn't entirely controlled by you, there may be risks of code injection.

  1. If you prefer to stick to using New Function, ensure you include a return statement and then execute it to unwrap the wrapper:

const a = () => {
  return "hello world"
}
const aString = a.toString()
const b = new Function("return " + aString)();
console.log(b());  // "hello world"

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

When I send data using axios, I receive the response in the config object instead of the data

Currently, my web app is being developed using NextJS NodeJS and Express. I have set up two servers running on localhost: one on port 3000 for Next and the other on port 9000 for Express. In the app, there is a form with two input fields where users can e ...

CKFinder Error: Unable to find definition for t.event.special.swipe

Upon using CKFinder 3.2.0 with Firefox 44.0, I encountered the following error message. Interestingly, this issue is exclusive to Firefox while Chrome works perfectly fine. Any insights on what could be causing this problem and how it can be resolved? Ty ...

Form an array using the values that are returned

As I iterate through an object and extract elements, my console.log displays: ["item 1"] ["item 2"] ["item 3"] and so on. All I want is to create a new array formatted like this: ["item 1","item 2","item 3"]; ...

evaluating each element in a list against another

I'm attempting to check if an element exists in another list, but the lists are not in order and they are of different sizes. let list1 = [10 , 4 , 5] let list2 = [4 , 5] I attempted a solution, however it only works when the elements are in the same ...

Assigning an identification number to specify the type of Chip

I am currently working on a project involving Material UI "Chips" that contain text and serve as references. Within the context of my project, I have Chips for both White Advantages and Black Advantages sections. However, there are instances where these Ch ...

Important notice: It is not possible to assign refs to function components. Any attempt to do so will result in failure. If you intended to assign a ref, consider

My console is showing a warning when I use the nextJs Link component. Can someone assist me in resolving this issue and providing an explanation? Here is the message from the console: https://i.stack.imgur.com/jY4FA.png Below is a snippet of my code: im ...

Struggling to send POST request from Bootstrap form to Node server

I am currently in the process of setting up a MEN application using the clean blog bootstrap template available at Recently, I integrated a new post functionality into the template. When testing the form submission, I noticed that I receive the JSON objec ...

JavaScript function to close mobile menu when menu item is clicked

https://i.sstatic.net/GfKem.png I have a dilemma with my HTML code. I am trying to figure out how to collapse the menu when clicking on a menu item using JavaScript. I have been stuck on this for two days now. Can anyone provide a solution with an explanat ...

html css javascript, Is it possible to execute a script before a webpage finishes loading?

My current setup is similar to a lightbox feature, but I'm facing an issue where the script waits for the entire webpage to load before running. Is there a way to ensure that my script runs first without waiting for the webpage to fully load? CSS: # ...

What sets apart calling an async function from within another async function? Are there any distinctions between the two methods?

Consider a scenario where I have a generic function designed to perform an upsert operation in a realmjs database: export const doAddLocalObject = async <T>( name: string, data: T ) => { // The client must provide the id if (!data._id) thr ...

How can I use Angular to dynamically open a video that corresponds to a clicked image?

I need assistance with a functionality where clicking on an image opens a corresponding video on the next page. The issue is that all images have the same ID, making it difficult to link each image to its respective video. Below is the data I am working ...

Connect an angular directive template to an event

In my Angular directive, the template structure is as follows: <Button id="testBtn">Test me<button> Within the directive controller, I have defined API functions for the directive. Now, I need to send an event to the parent module when the bu ...

How can I utilize jQuery to save a simple text string in a mySQL database?

Seeking guidance on this jQuery code snippet: $('.bggallery_images').click(function () { var newBG = "url('" + $(this).attr('src'); var fullpath = $(this).attr('src'); var filename = fullpath.replace('im ...

Which prop type should I verify when needing to specify the source?

Currently, I am working on a project that involves react native. To ensure the proper type checking of components, I am utilizing prop-types. My current task is to encapsulate the Image component from react-native within my own custom Image component. Belo ...

Stopping React component click event from bubbling up to document

How do I prevent a click event in a React component from bubbling up to the document? There seems to be an issue that needs fixing! Let's see if we can resolve it on our own. I have a box component with a click event listener, and some link compone ...

Plunker fails to run simple AngularJS demo

I'm having trouble figuring out why this basic example isn't functioning as expected on Plunker. http://plnkr.co/edit/EfNxzzQhAb8xAcFZGKm3?p=preview var app = angular.module("App",[]); var Controller = function($scope){ $scope.message ="Hel ...

Decline the input according to the percentage

After experimenting with the script, I discovered that it did not perform as expected (even though it works on Google Webapp's script HTML form). My goal is to invalidate an input if the Downpayment is less than 30% or more than 100% of the Price, in ...

Can the keypress event be modified within the Google Chrome browser?

My code is functioning in IE but not in Chrome. I am having issues with the event not changing. Is there a different method for achieving this in Chrome, rather than assigning specific values to the charCode, keyCode, and which variables? You can view my ...

The Angular scope remains static during service calculations and does not reflect immediate updates

Is there a way to display a message on the scope indicating that a function in a service is currently being calculated and taking a long time? I have set up a simplified example in this jsfiddle: http://jsfiddle.net/rikboeykens/brwfw3g9/ var app = angul ...

JavaScript Method for Retrieving Form Element Values

I am currently working on retrieving the value of an input element in a popup window that is launched from a parent page. Here is my code, but I am facing difficulties in obtaining the pc value from the input field. <html> <head> <? $pid= ...