Is there a way that treat javascript function with dynamic name?

Viewed 47

I want to use function in my javascript code in dynamic way like this code.

const function1 = (param) => {
    return "AA" + param
}
const function2 = (param) => {
    return "BB" + param
}
const function3 = (param) => {
    return "CC" + param
}

for (let i=1; i < 4; i++) {
    // call function1, 2, 3 with i
} 

And I saw a similar case in python like this.

note1 = "note1"
note2 = "note2"
note3 = "note3"

for i in range(1, 4):
    print(vars()[f"note{i}"])

like this python case, Is there a way that treat javascript variable or function with dynamic name?

1 Answers

You can do like this:

Any function that is created outside any function, in non-strict mode, goes to default this (window). So you can access it as window[ propertyName ]. However, its a bad practice to pollute to window object. Hence better option is to wrap these functions in a custom object and then use same syntax to access functions.

const function1 = (param) => {
    return "AA" + param
}
const function2 = (param) => {
    return "BB" + param
}
const function3 = (param) => {
    return "CC" + param
}


for (let i=1; i < 4; i++) {
    window[`function${i}`](i);
}

Reference:

Related