Search code examples
javascriptecmascript-6string-interpolation

Using string interpolation for function call


Is there a way to call the following function using ES6 syntax:

let type = 'Line'
new Chartkick.${ type }Chart(el, this.data)

with the hopes of generating:

new Chartkick.LineChart(el, this.data)

Solution

  • No, you don't need any string interpolation for this. It's just standard dynamic property access with bracket notation:

    new Chartkick[type+"Chart"](el, this.data);
    

    Of course you could use an ES6 template literal instead of the string concatenation, but I don't think it boosts readability a lot:

    new Chartkick[`${ type }Chart`](el, this.data);