Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inconsistent type for JavaScript ES6 template strings

While testing JavaScript ES6's new template strings (in Firefox, if it matters), I noticed some inconsistencies in their types.

I defined a custom function, like this:

function f(a) {
    console.log(typeof(a));
    console.log(a);
}

First, I tested the function "normally", using parentheses around the template string.

f(`Hello, World!`)

As expected, this yielded a type of string and Hello, World! was outputted to the console.

Then I called the function shorthand, without the parentheses, and inconsistencies occurred.

f`Hello, World!`

The type became object, and Array [ "Hello, World!" ] was outputted to the console.

Why was the template string wrapped in an array when using the second method? Is this just a bug in Firefox (ES6 is a new standard, after all) or is this behavior expected for some reason?

like image 917
jrich Avatar asked Aug 28 '15 20:08

jrich


People also ask

What are ES6 template strings?

Backtick basics. ES6 introduces a new kind of string literal syntax called template strings . They look like ordinary strings, except using the backtick character ` rather than the usual quote marks ' or " . In the simplest case, they really are just strings: context.

What is the correct syntax of template strings in JavaScript?

Template literal is created using the backtick (`) character. Syntax: var s=`some string`; Multiline Strings: In-order to create a multiline string an escape sequence \n was used to give new line character.

How do you break a line in template literal?

New Line Using Template Literals : For creating a new line in the console, you can also insert a new line break by pressing Enter while using the template literals.

What is `` in JS?

Although single quotes and double quotes are the most popular, we have a 3rd option called Backticks ( `` ). Backticks are an ES6 feature that allows you to create strings in JavaScript. Although backticks are mostly used for HTML or code embedding purposes, they also act similar to single and double quotes.


1 Answers

// A function call, passed the result of a template literal.
f(`str`)

and

// A tagged template call, passed metadata about a template.
f`str`

are not the same. The first calls f with single string as an argument. The second calls f with several parameters, depending on the template. e.g.

f`one${2}three${4}five`

would pass f

f(strings, ...values)

with

strings
// ['one', 'three', 'five']

which is a list of all of the string sections of the template, and

values
// [2, 4]

which are all of the values that fit between the strings. This allows tags to preprocess the string and process it.

The documentation on MDN can help more.

like image 51
loganfsmyth Avatar answered Nov 03 '22 00:11

loganfsmyth