0

I am doing the "30 Day Vanilla JS Coding Challenge" : https://javascript30.com/

There is code line in the first exercise :

function playSound(e) {
    const audio = document.querySelector(`audio[data-key="${e.keyCode}"]`);
}

1 - why does he uses the "backquote" (`) insted of simple single or double quote? (" or ') ?

2 - What does the curly brace and dollar sign means here? ${e.keyCode}

I do not get this syntax for Javascript...

Thanks!

brsastre
  • 35
  • 1
  • 7
  • 1. Is [Template Literals](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals) (new(er) feature). 2. See 1. – Mark C. Jan 02 '18 at 00:29
  • Most languages offer something similar, in Ruby it's almost identical `"My name is #{name}!"`. Python: `"My name is {}".format(name)`, etc. – Jared Smith Jan 02 '18 at 00:33

4 Answers4

0

That is the syntax for what is called a "Template Literal", you can find the documentation for it here

Collin G.
  • 466
  • 2
  • 9
0

Those are template literals enclosed by the back-tick (grave accent) character. Template literals can contain placeholders, enclosed by the dollar sign and curly braces (${expression}). The expressions in the placeholders are evaluated and put in place into the string. In this case they are also helpful to avoid escaping the quotes in the string literal.

So in this code ${e.keyCode} will become the actual key code and be interpolated in the string. For example if e.keyCode is 65 the expression will be equivalent to document.querySelector('audio[data-key="65"]');

mdatsev
  • 3,054
  • 13
  • 28
0

Template Literals

Template literals are string literals allowing embedded expressions. You can use multi-line strings and string interpolation features with them. They were called "template strings" in prior editions of the ES2015 specification.

${e.keyCode} is string interpolation - the expression inside ${...} (in this case e.keyCode) is interpolated into the string -- it's replaced with the evaluated result in the final string.

Austin Brunkhorst
  • 20,704
  • 6
  • 47
  • 61
0

This is called interpolation. Don’t be scared, it’s just a syntax sugar.

var str = "bar"
console.log("foo" + str + "baz"); // foobarbaz
console.log(`foo${str}baz`); // foobarbaz
Kit Isaev
  • 680
  • 8
  • 19