Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

136
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda