7

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?

1
  • 1
    Try console.log`a ${1} b ${2} c`; to understand better what's happening. By omitting the parenthesis, you've completely change the meaning of your statement: you're not simply calling the function any more, but you're using a tagged template. Yep, this syntax sucks. Commented Aug 28, 2015 at 20:54

1 Answer 1

2
// 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.

Sign up to request clarification or add additional context in comments.

9 Comments

From a 36k rep users, I'd expected at list a link to the specification. A bit disappointed.
Thanks for the help! I've suggested an edit to add that this syntax is called tagged template strings, as I've learned from @Blackhole's comment, to help future searchers. This answer was helpful and informative.
@UndefinedFunction: It's called "tagged template" (no "string"). I think it's a bit misleading to call the "strings" (official they are called "tagged template" and "template literal"), especially since tagged templates don't necessarily result in strings at all.
@FelixKling hmmm, interesting. The MDN said "tagged template strings", so that's why I called them that.
@UndefinedFunction: Yep. I'm not particular happy about that ;) ecma-international.org/ecma-262/6.0/…
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.