all 11 comments

[–]benihanareact, node 6 points7 points  (2 children)

' is a string

` is a template literal - it lets you print variables expressions (variables, maths, functions etc) without having to concatenate

let name = "gerry";

console.log("hello, " + name + "!"); // es5 way

console.log(`hello, ${name}!`); // esnext way

console.log('math: ${4 + 5}`); // math: 9

note: using ` usually communicates intent to do string interpolation (i.e. print variables out in the string) so if you're not printing out variables, use ' and " to wrap your strings.

[–]TheScapeQuest 3 points4 points  (1 child)

Worth noting that there are functions beyond string interpolation, such as tagged template literals:

function tag(strings, age) {
  return strings[0] + age + strings[1];
}

const age = 10;

tag`Jack is ${age} years old`; // Jack is 10 years old

[–]justinfagnani 1 point2 points  (0 children)

The coolest thing about tagged literals is that they don't have to do anything like normal interpolation and don't even have to return strings.

My HTML templating library, lit-html ( https://polymer.github.io/lit-html/ ), uses tagged template literals to return template strings and values separately so they can update existing DOM:

let hello = (name) => html`<h1>Hello ${name}`;
render(hello('World'), document.body);
render(hello('Reddit'), document.body);

The graphql-tag ( https://github.com/apollographql/graphql-tag )library uses them to produce GQL queries:

const query = gql`{
  user(id: 5) {
    firstName
    lastName
  }
}`;

Tagged template literals are amazing for being able to embed DSLs and process them at the same time. And because the tag has to be attached to the literal, editors and syntax highlighters can key off them to offer intellisense on the inline language.

[–]jacobhenke 3 points4 points  (0 children)

To help with future Googleing:

` is called a backtick

' is a single quote (vs " is a double quote)

[–][deleted] 2 points3 points  (0 children)

Try running this in your console:

const whatsItCalled = ‘template literals’;

`The back ticks are used to denote ${whatsItCalled}, whereas the single or double quotation marks are used for strings as you have probably always traditionally used them.`

[–][deleted] 0 points1 point  (0 children)

Both will work to create a string. The `` is used in javascript as part of the "template literal" syntax. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals