Skip to content

Instantly share code, notes, and snippets.

@codetricity
Last active October 4, 2018 13:32
Show Gist options
  • Select an option

  • Save codetricity/ef02297195a65602ce33ab27f0580845 to your computer and use it in GitHub Desktop.

Select an option

Save codetricity/ef02297195a65602ce33ab27f0580845 to your computer and use it in GitHub Desktop.
ES6 template strings

Using JavaScript Template Strings

  1. create a new project with index.html, main.js, and d3.js

  2. modify index.html. Add id='introduction' to a div tag below the opening <body> tag.

    <script src='js/d3.js'></script> <script src='js/main.js'></script>

Key syntax: ${value}

Add variables to the top of the main.js file.

let name = "Shel Silverstein";
let title = 'Snowball';

Old method of string concatenation with plus signs

Run the following command.

    console.log("We'll study the poem " + title + " by " + name);
  • harder to read.
  • spacing before and after variables is prone to error

New ES6 is easier to read and easier to get spacing correct.

console.log(`We'll study the poem ${title} by ${name}`);

long lines of text

previously difficult before back-tick feature. The string below can span multiple lines.

    let poem = `I made myself a snowball
    As perfect as could be.
    I thought I'd keep it as a pet
    And let it sleep with me.
    I made it some pajamas
    And a pillow for its head.
    Then last night it ran away,
    But first it wet the bed.`

Question: Is it okay to use single quotes inside of the backtick? What about double quotes?

Test Output

Question: in the line below, what does \n do?

console.log(`Here's ${title} by ${name}\n\n${poem}`);

integrating numbers

let width = 400;
let safeZone = 100;

console.log(`invalid number. Max number is ${width + safeZone - 50}`);

objects

const margin = {left: 100, top: 200, bottom: 50, right: 50};

console.log(`horizontal buffer is ${margin.left + margin.right}`);
console.log(`vertical buffer is ${margin.top + margin.bottom}`);

HTML insertion

Before getting to HTML insertion, practice HTML.

in the index.html file, add the title and author of the poem.

Review these HTML elements:

  1. h1, h2, h3
  2. b, em, pre
  3. p
  4. div
  5. table

populate table with:

author title note
Shel Silverstein Snowball humorous

old way

let introduction = document.getElementById('introduction');
introduction.innerHTML = '<h1>' + title + '</h1>' + 
    '<h3>by ' + name + '</h3>';

new way

introduction.innerHTML = `
    <h1> A poem called <em> ${title}</em> </h1>
    <h3> by ${name}</h3>
    <pre style="font-family:arial">${poem}</pre>
    `
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment