Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

713
Vistas
Backticks (`…`) calling a function in JavaScript

I'm not sure how to explain this, but when I run

console.log`1`

In google chrome, I get output like

console.log`1`
VM12380:2 ["1", raw: Array[1]]

Why is the backtick calling the log function, and why is it making a index of raw: Array[1]?

Question brought up in the JS room by Catgocat, but no answers made sense besides something about templating strings that didn't really fit why this is happening.

over 4 years ago · Santiago Trujillo
3 Respuestas
Responde la pregunta

0

It is called Tagged Template in ES-6 more could be read about them Here, funny I found the link in the starred section of the very chat.

But the relevant part of the code is below (you can basically create a filtered sort).

function tag(strings, ...values) {
  assert(strings[0] === 'a');
  assert(strings[1] === 'b');
  assert(values[0] === 42);
  return 'whatever';
}
tag `a${ 42 }b`  // "whatever"

Basically, its merely tagging the "1" with console.log function, as it would do with any other function. The tagging functions accept parsed values of template strings and the values separately upon which further tasks can be performed.

Babel transpiles the above code to

var _taggedTemplateLiteralLoose = function (strings, raw) { strings.raw = raw; return strings; };

console.log(_taggedTemplateLiteralLoose(["1"], ["1"]));

As you can see it in the example above, after being transpiled by babel, the tagging function (console.log) is being passed the return value of the following es6->5 transpiled code.

_taggedTemplateLiteralLoose( ["1"], ["1"] );

The return value of this function is passed to console.log which will then print the array.

over 4 years ago · Santiago Trujillo Denunciar

0

Tagged template literal:

The following syntax:

function`your template ${foo}`;

Is called the tagged template literal.


The function which is called as a tagged template literal receives the its arguments in the following manner:

function taggedTemplate(strings, arg1, arg2, arg3, arg4) {
  console.log(strings);
  console.log(arg1, arg2, arg3, arg4);
}

taggedTemplate`a${1}b${2}c${3}`;

  1. The first argument is an array of all the individual string characters
  2. The remaining argument correspond with the values of the variables which we receive via string interpolation. Notice in the example that there is no value for arg4 (because there are only 3 times string interpolation) and thus undefined is logged when we try to log arg4

Using the rest parameter syntax:

If we don't know beforehand how many times string interpolation will take place in the template string it is often useful to use the rest parameter syntax. This syntax stores the remaining arguments which the function receives into an array. For example:

function taggedTemplate(strings, ...rest) {
  console.log(rest);
}

taggedTemplate `a${1}b${2}c${3}`;
taggedTemplate `a${1}b${2}c${3}d${4}`;

over 4 years ago · Santiago Trujillo Denunciar

0

Late to the party but, TBH, none of the answers give an explanation to 50% of the original question ("why the raw: Array[1]")

1. Why is it possible to call the function without parenthesis, using backticks?

console.log`1`

As others have pointed out, this is called Tagged Template (more details also here).

Using this syntax, the function will receive the following arguments:

  • First argument: an array containing the different parts of the string that are not expressions.
  • Rest of arguments: each of the values that are being interpolated (ie. those which are expressions).

Basically, the following are 'almost' equivalent:

// Tagged Template
fn`My uncle ${uncleName} is ${uncleAge} years old!`
// function call
fn(["My uncle ", " is ", " years old!"], uncleName, uncleAge);

(see point 2. to understand why they're not exactly the same)

2. Why the ["1", raw: Array[1]] ???

The array being passed as the first argument contains a property raw, wich allows accessing the raw strings as they were entered (without processing escape sequences).

Example use case:

let fileName = "asdf";

fn`In the folder C:\Documents\Foo, create a new file ${fileName}`

function fn(a, ...rest) {
  console.log(a); //In the folder C:DocumentsFoo, create a new file
  console.log(a.raw); //In the folder C:\Documents\Foo, create a new file 
}

What, an array with a property ??? ???

Yes, since JavaScript arrays are actually objects, they can store properties.

Example:

const arr = [1, 2, 3];
arr.property = "value";
console.log(arr); //[1, 2, 3, property: "value"]

over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda