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
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.
From MDN Tagged templates:
Tags allow you to parse template literals with a function. The first argument of a tag function contains an array of string values. The remaining arguments are related to the expressions.
The tag function can then perform whatever operations on these arguments you wish, and return the manipulated string.
It might seem to be an unusual construct, but your code demonstrates how it works.
The strings argument is an array ['Num1 ', 'Num2 ', 'Num3 ', ''], which are the literals before, between, and after the expressions, and the values are the evaluated expressions [15, 20, 2].