Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

140
Views
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

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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.

about 4 years ago · Juan Pablo Isaza Report

0

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].

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!