Search code examples
javascriptstringfunctionparameterseval

calling function using its name as a string and using replacing parameters with an array


Here is my example for better understanding of my question. lets say:

var a = ["Hello", "World"];
var b = "Hi";

How can I do:

console.log(b."concat"(a)); // and return HiHelloWorld

I tried doing this:

console.log(b.eval("concat").apply(this, a));

but it gives me an error saying that b.eval is not a function. Please note that my primary goal is not to concatenate strings. This is just an example. I want to be able to do this with any function...

Thank You


Solution

  • You can use the [] syntax together with the spread operator ....

    var a = ["Hello", "World"];
    var b = "Hi";
    
    console.log(b["concat"](...a));