Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dollar sign followed by a square bracket in a template string

I was messing around with some ES6-code and came across this

let vendors = ['ms', 'moz', 'webkit', 'o'];
let root = window || global;
let performance = window.performance || {};
if (!performance.now) {
  vendors.some(function(vendor) {
    performance.now = performance[`$[vendor}Now`];
    ...

I can guess what the code-piece below does, but what kind of library/syntax is it? It's not something I have ever seen before, and it's not pure ES6, right?

`$[vendor}Now`
like image 763
Alfred Gårdeskog Avatar asked Dec 19 '22 00:12

Alfred Gårdeskog


1 Answers

It seems that this is a syntax error. The correct thing should be:

`${vendor}Now`

This is the dollar expression as it is mentioning here: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/template_strings

Template strings are enclosed by the back-tick (`) (grave accent) character instead of double or single quotes. Template strings can contain place holders. These are indicated by the Dollar sign and curly braces (${expression}).

The square bracket in a template string is a mistake.

More specifically if you have:

var expression = 'test';

console.log(`string text ${expression} string text`); //Correct syntax

The above code will export: "string text test string text"

But the below code with one opening square bracket and one closing curly bracket

var expression = 'test';

console.log(`string text $[expression} string text`); //Wrong syntax

Will just export: "string text $[expression} string text"

like image 142
mikelamar Avatar answered Dec 22 '22 09:12

mikelamar