Template literals and pathentheses-less function calls

codemonkey

I recently learned that ES6 allows to make function calls without parentheses when using a template literal as a parameter. E.g.

showstring`Hello World`;

After reading a few articles on this functionality, however, I have come away with scant information as to the logic behind how JS handles these calls.

After playing around with some permutations of my code, I am still struggling to piece together the pattern of how a template literal is broken down inside the function when one calls it that way.

const showstring = (str) => {
  console.log(str);
}
showstring`Hello World`;

What happens in the above code is straightforward, the string literal is received as an array where the first and only element is the string.

Where it gets a bit confusing is once I start using expressions inside the template. E.g.

const showstring = (str, ...values) => {
  console.log(str);
  console.log(values)
}
const name = 'John'
showstring`Hello World ${name} ${name} ${1 + 2} and more`;

So it looks like the ..values part de-scrutures all the expressions. But why, then, does the str array have empty strings in those spots?

I just don't fully grasp the pattern it follows here. Can someone explain this feature? Or perhaps point me to a good article?

mts knn

In the second code snippet, these are logged:

// str
[
  "Hello World ",
  " ",
  " ",
  " and more"
]

// values
[
  "John",
  "John",
  3
]

If by those "empty strings" you mean the 2nd and 3rd item of the str array, they are not empty strings; they are strings with a single space. They come from the spaces between the expressions in the template literal:

showstring`Hello World ${name} ${name} ${1 + 2} and more`;
//                            ^       ^

When a template literal is preceded by an expression – in this case showstring – it's called a tagged template.

In your showstring function, str contains always one more item than the values array. E.g. take a look at what these log:

const showstring = (str, ...values) => {
  console.log(str);
  console.log(values)
}
const name = 'John'
showstring``;
showstring`${name}`;
showstring`Hello ${name}!`;

This isn't specific to your function; this is how tagged templates work. From the Tagged templates section in the book JavaScript for impatient programmers (ES2020 edition):

The function before the first backtick is called a tag function. Its arguments are:

  • Template strings (first argument): an Array with the text fragments surrounding the interpolations ${}.
  • Substitutions (remaining arguments): the interpolated values.

About your comment:

Interestingly though, that single space will always remain a single space no matter how many spaces you put between the expressions when calling the function. Any idea why it trims to just one space?

This doesn't seem to be the case. This logs a string with three spaces:

const showstring = (str, ...values) => {
  console.log(str);
  console.log(values)
}
const name = 'John'
showstring`Hello ${name}   ${name}!`;

Were you maybe printing the results to the DOM? Multiple spaces are shown as only one unless you are using <pre> or white-space: pre; or something similar, so it might seem that the results are trimmed to just one space.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Template literals and parentheses-less function calls

Javascript template literals - function call

function calls in template arguments

What is the default “tag” function for template literals?

Map function and referring to variables inside template literals

Template that calls member function on argument

How to make a call to a template function less verbose

What is the purpose of template literals (backticks) following a function in ES6?

Using onclick event with a function with more than one argument in Template literals

Angular - *ngIf vs simple function calls in template

Order of function calls in variadic template expansion

How to use template literals (``) within template literals?

Why do argument-less function calls execute faster?

Typescript template literals with inference

Template Literals with a ForEach in it

Evaluating template literals dynamically

template literals in jsx

Template Literals with Javascript Replace?

For Loop inside Template Literals?

JS This and Template Literals Practice

Template Literals for Javascript Arrays

Tagged Template Literals in JavaScript

Template literals (Template strings) didn't give the exact result in arrow function

Using Template Literals with Lodash _.template()

How to define and use std::less as a template argument in a function definition?

Concatenate function calls with a template lambda C++20

Can calls to member functions of function parameters be used as template arguments?

Unified function calls for instances and primitive types using template specialization and interfaces

How to prevent using function calls in Angular template expressions

TOP Ranking

  1. 1

    Failed to listen on localhost:8000 (reason: Cannot assign requested address)

  2. 2

    Loopback Error: connect ECONNREFUSED 127.0.0.1:3306 (MAMP)

  3. 3

    How to import an asset in swift using Bundle.main.path() in a react-native native module

  4. 4

    pump.io port in URL

  5. 5

    Spring Boot JPA PostgreSQL Web App - Internal Authentication Error

  6. 6

    Can't pre-populate phone number and message body in SMS link on iPhones when SMS app is not running in the background

  7. 7

    Do Idle Snowflake Connections Use Cloud Services Credits?

  8. 8

    maven-jaxb2-plugin cannot generate classes due to two declarations cause a collision in ObjectFactory class

  9. 9

    Binding element 'string' implicitly has an 'any' type

  10. 10

    BigQuery - concatenate ignoring NULL

  11. 11

    Compiler error CS0246 (type or namespace not found) on using Ninject in ASP.NET vNext

  12. 12

    In Skype, how to block "User requests your details"?

  13. 13

    Jquery different data trapped from direct mousedown event and simulation via $(this).trigger('mousedown');

  14. 14

    Pandas - check if dataframe has negative value in any column

  15. 15

    flutter: dropdown item programmatically unselect problem

  16. 16

    Generate random UUIDv4 with Elm

  17. 17

    Is it possible to Redo commits removed by GitHub Desktop's Undo on a Mac?

  18. 18

    ngClass error (Can't bind ngClass since it isn't a known property of div) in Angular 11.0.3

  19. 19

    Change dd-mm-yyyy date format of dataframe date column to yyyy-mm-dd

  20. 20

    EXCEL: Find sum of values in one column with criteria from other column

  21. 21

    How to use merge windows unallocated space into Ubuntu using GParted?

HotTag

Archive