How can you run a function in JavaScript or TypeScript that is stored as a string?

Is there a way to call a function that is stored as a string? For example:

var dynamicFun = `function Hello(person) {   return 'Hello' + person; }`

In this case, the dynamicFun variable can store any function definition dynamically, such as:

var dynamicFun = `function Sum(num) {   return num + num; }`

During compile time, I am not aware of which function definition is assigned to the dynamicFun variable. It gets assigned at runtime. So how can I call these functions using the dynamicFun variable with parameters (without knowing the actual function name or definition) in JavaScript/TypeScript?

Answer №1

Have you considered using the Eval Global Function in JavaScript for this task?

It's worth noting that relying on eval() is generally frowned upon due to security concerns. Is there a specific reason you are exploring this approach? There may be alternative solutions that are more secure and efficient.

Check out the documentation on MDN for more information about eval()

console.log(eval('2 + 2'));
console.log(eval('"Hello" + " " + "World"'));

I hope this insight proves helpful for your inquiry!

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

What is the best way to stop this Jquery slider from moving?

I've been struggling with this issue for what feels like forever, and it's driving me crazy! I have a slider on the homepage that I'm trying to enhance with a "click to pause" feature (and maybe even a click to resume, for good measure). I ...

The Angular modal service is failing to show up on the screen

I am having trouble implementing the angular modal service in my web application. When I click on the button, the modal does not appear. Can someone help me figure out what I am doing wrong? Builder View <div ng-controller="BuilderController as vm"> ...

What is the significance of `new?()` in TypeScript?

Here is a snippet of code I'm working with in the TypeScript playground: interface IFoo { new?(): string; } class Foo implements IFoo { new() { return 'sss'; } } I noticed that I have to include "?" in the interface met ...

Tips for effectively handling a prop in an HTML form using Vue.js and avoiding infinite loops with a computed property

I have a Vue.js form for signing up that features numerous similar fields. From my understanding, I should initialize the values as props rather than objects or arrays (since they will be pass-by-value). My approach involves using a computed property with ...

"Implementing constraints in Postgres using Node.js

Currently, I am struggling with writing a constraint code to handle situations where a user tries to search for an id that does not exist in the database (specifically PostgreSQL). Despite my efforts, the if statement in the code below does not seem to be ...

Vue automatically clears the INPUT field when disabling it

Have you ever noticed why Vue resets a text input field when it's set to disabled? This behavior is not observed with plain Javascript and also doesn't affect textarea fields. var app = new Vue({ el: '.container', data: { disab ...

Angular: Navigating through two levels of fetched data from Firebase

I'm currently working on parsing retrieved data from Firebase within an Angular (Typescript) project. The structure of my JSON data in Firebase resembles the following: "customer" : { "customerId1" : { "documents" : { "documentId1" : { ...

The back button on an Angular JS application should display a confirmation dialog when pressed

I am currently working on an AngularJS mobile app that consists of various modules. One of my requirements is to access the device's back button within the application, and I also need a dialog with "OK" and "Cancel" options. Clicking on "OK" should ...

The jQuery resize() method seems to be malfunctioning

My jQuery resize function is not working properly. I am trying to implement a custom scroll for devices with a width of 767, but it doesn't seem to be functioning as expected. Normally, the scroll works on devices above 767 in width. How can I fix thi ...

JavaScript Processing Multiple Input Values to Produce an Output

Hello, I am working on creating a stamp script that will allow users to enter their name and address into three fields. Later, these fields will be displayed in the stamp edition. Currently, I have set up 3 input fields where users can input their data. He ...

Demonstrating a feature in a custom Angular Material dialog box

I have a reusable custom Material UI Dialog that I want to utilize to show different components. For instance, I would like to display a Login component on one occasion and a Registration component on another. However, the issue arises when I assign my com ...

How can you fix the "bad value" response in mongodb when utilizing query parameters in the url?

{ "ok": 0, "code": 2, "codeName": "BadValue", "name": "MongoError" } Whenever I attempt to use query parameters skip and limit in the url, this error message pops up. localhost:5 ...

Tips for inputting information without redundancy after selecting a specific designation

I'm experiencing a challenge with this code as it repeats when already chosen. My goal is to add data in the database once something has been selected. When I click on spin, the randomizer will choose a name and update their status to "done". Subsequ ...

What is the most efficient method for examining dependencies in Yarn 2 (berry)?

Is there a way to check for vulnerabilities in Yarn 2 dependencies? In Yarn 1.x, you could run yarn audit, similar to npm audit. However, this command is not available in Yarn 2. According to this issue on the Yarn berry Github, it may not be implemented ( ...

The error message "Declaration file for module 'mime' not found" was issued when trying to pnpm firebase app

Currently, I am in the process of transitioning from yarn to pnpm within my turborepo monorepo setup. However, I have run into an issue while executing lint or build commands: ../../node_modules/.pnpm/@<a href="/cdn-cgi/l/email-protection" class="__cf_e ...

Puppeteer has a limit of running only three instances on Heroku

Currently, I am in the process of developing a website that employs puppeteer to extract information from another site. The npm server works flawlessly on my local machine, but once deployed on Heroku, it halts after processing the first three files. The ...

Interactions of selecting dates in datepicker widget

Currently, I am working on developing my personal work website. One issue I have encountered is with the calendar feature. The "From" date can be selected before today's date, which is not ideal. Additionally, if a date 5 days from now is chosen as th ...

Try uploading a file with the imageUpload function in JavaScript, could be something basic

Today I successfully uploaded a picture using a basic button (id: "imageUpload") to select and upload a file. Everything worked flawlessly, with the thumbnail of the picture appearing in "thumb1." Now, I am attempting to allow users to upload a picture by ...

Working with Variables in Handlebars with Node.js

Is it possible to reference an object key with a space in a handlebars view? The specific key is "Record Number" within the object, but I am encountering difficulties when trying to reference it in the view. Here's the code snippet from the view: {{# ...

Using Bootstrap to present information with a table

Presenting information in a Bootstrap table with Vue.js I have gathered the necessary data and now I want to showcase it in a table using bootstrap. Currently, I have achieved this using SCSS as shown in the image below: Although I am not proficient in J ...