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?
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.
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.
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.
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.
// 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With