Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

161
Views
Is there a way to access a defined function by adding its name in the form of a string and executing it later?

I know that functions are objects, and objects never equal each other, even if they are identical. The question that I have is that, let's say I have a function as follows:

const xyz = () => a + b;

Can I access this function somehow using this code below or something similar:

const func = `x + y + z`;

And then later execute it like a normal function? Is there a library or tool that I can use?

func()

I am using Javascript.

I am building a small project and am importing functions from a file where they are already defined. I want those functions to run when a user clicks a specific button. The text of the button plus an additional string can be joined to make the name of that fucntion. Now I want to run that function using the name but it ends up in error. Here is the code of what I am trying to do.

import "./style.css";
import tabs from "./tab.js";
import {biryaniTabChange, pulaoTabChange} from "./dishTexts.js";


tabs.heading();
tabs.createTab();
tabs.appendDish("Biryani");
tabs.appendDish("Pulao");
tabs.appendDish("Aloo Matar");
tabs.dishDiv();
let dishes = document.querySelectorAll(".dishes");
document.addEventListener('click', (e) => {
    if (!e.target.classList.contains('dishes')) return;
    if (!e.target.closest('div').classList.contains('tabs')) return;
    let func = new Function(e.target.textContent.toLowerCase().replace(/\s+/g, '') + "TabChange");
    console.log(func);
    e.target.addEventListener('click', func())
})
window.onload = () => {
    biryaniTabChange();
}
about 4 years ago · Santiago Trujillo
1 answers
Answer question

0

First import every function into one namespace object:

import * as fns from "./dishTexts.js";

Then you can access them by name with the string:

const name = 'biryaniTabChange'
fns[name]()

or just

fns['biryaniTabChange']()

And your final code will look something like this:

const name = e.target.textContent.toLowerCase().replace(/\s+/g, '') + "TabChange"
const func = fns[name]
e.target.addEventListener('click', func) // no call here!

Based on the sample you provided

about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!