Search code examples
javascripttemplate-literals

Tagged Template Literals in JavaScript


Dipping a toe into JavaScript. After C, C++ and Python, JavaScript is like wild west. Can someone explain why do I get the output that doesn't make any sense:

var a = 5;
var b = 10;

function foo(strings, ...values) {
    let a = values[0];
    let b = values[1];

    return `Sum ${a + b} Product ${a * b}  Division ${b / a}`;
}

console.log(foo`Num1 ${a + 10} Num2 ${b * 2}  Num3 ${b / a}`);

The output: Sum 35 Product 300 Division 1.3333333333333333


Solution

  • The values presented to you in the function are the following:

    let strings = ['Num1 ', ' Num2 ', '  Num3 ', ''];
    let values = [15, 20, 2]; // a+10, b*2, b/a
    

    You are returning:

    `Sum ${15 + 20} Product ${15 * 20}  Division ${15 / 20}`
    

    This is expected as it evalulated the templates and then ran them inside the tag as well.