Template Literals and First Class Citizens

String Interpolation with Template Literals

As we dig deeper into HTML-in-JavaScript, you'll notice that standard String concatenation gets to be a bit cumbersome. Instead of using the concatenation operator (+), most String manipulation in modern JS is done with template literalsarrow-up-right and String interpolation. The idea is that we can inject variables or expressions directly into a template, rather than piecing together substrings manually. The template literal version of the exercise above would look like this:

const firstName = prompt("Hi there! What's your first name?")";
const lastName = prompt("What's your last name?")";
const output = document.querySelector("#greeting");

output.innerHTML = `<p>Thanks for visiting, ${firstName} ${lastName}.</p>`;

Notice how this syntax maintains the structure of our HTML more accurately. This is true of multi-line HTML chunks as well, since template strings take newlines into account! If we wanted to make our output's innerHTML' a bit more fancy, we could have re-written that last line like so:

output.innerHTML = `
  <div>
    <p>
      Thanks for visiting,
      <span class="some-class">
        ${firstName} ${lastName}
      </span>
    </p>
  </div>
`;

Which is much nicer, don't you think? You can imagine how we might be able to turn all of our existing HTML into a set of fancier templates using this method. Try refactoring all of your concatenated Strings into interpolated template literals instead!

Fun With Functions

Review

We've already seen a variety of functions, from built-in functions like console.log(), to a few of our own built using function functionName() {}. We've also already learned how to invoke or execute functions with (), as well as passing in a few simple arguments (like we've done with prompt("some string")).

a new syntax (part 1)

Up to this point, we've been writing functions like this:

While there are some technical differences between the two ways of declaring functions, the latter is used much more widely than the former, and is generally a bit easier to read. As long as we treat the functional expression the same way we were treating it's const-based cousin, we should be fine (and save ourselves a few keystrokes in the process).

the return keyword

Here's a function that returns a value without any side effects, meaning that invoking the function will have no affect anything outside of that function's _scope. (nothing outside of the { and }).

Functions are First Class Citizens

Functions are ‘first-class citizens’ afforded all of the rights and privileges of other data types. This means that they can be assigned as variables (function declarations - like variable declarations):

More importantly, they can be passed into other functions as arguments!

Last updated