An Independent Sitecore Learning Resource

Menu

Crash Course for Composable, Part 1: JavaScript Basics

Crash Course for Composable, Part 1: JavaScript Basics

Author

Brandon Bruno

Published

October 20, 2021

Tags

Welcome to Part 1 of the Crash Course for Composable series. To get started, let's review some basic JavaScript features from ES5 and ES6 that all developers should understand at a basic level.

What is modern JavaScript?

JavaScript is based on ECMAScript ("ES"), which standardizes features that JavaScript implements. Here's a brief history of JavaScript/ES versions:

  • ES1 (1997) - basic language syntax and features standarized
  • ES2 (1998) - tweaks / updates to spec standardization
  • ES3 (1999) - core enhancements
  • ES5 (2009) - strict mode, JSON support, let, etc.
  • ES6 (2015) - classes, modules, iterators, arrow functions, const, etc.

ES3 (1999 to 2009) was the era of Web 2.0 - AJAX, jQuery, light webapps, etc. - that built the modern web. The remainder of this article assumes that you are familiar with the basics of ES3 JavaScript - the syntax, functions as first-class citizens, variable hoisting, closures, etc.

There have been a bunch more updates to JavaScript/ES since 2015, but ES5 and ES6 feature the most significant updates that matter to the web in 2021 - that's the baseline for "modern JavaScript" that I aim to teach here.

What follows is a quick summary of key ES5 and ES6 features that are most-relevant and used for modern JS and React development.

Variable Scoping: var, let, const

Anyone who's even glanced at JavaScript code has seen the var keyword. This is the most basic way of declaring a variable:

var firstName = "Brandon";

Variables declared with var are globally scoped or to their nearest lexical scope. In a traditional browser environment, this is the window object (global) or a function body (lexical). var variables are also hoisted to the top of the nearest lexical scope (i.e. top of a function before execution begins). These quirks can sometimes make debugging JS applications difficult if the developer doesn't think like the interpreter.

Two new keyworks were introduced with ES5/ES6 to help tighten up the declaration of variables and make debugging a bit easier: let and const.

Let

The let keyword simplifies the complexities of var. There are two important differences that let brings to the table:

  • variables are only scoped to the block they were declared in (i.e. the current function block)
  • they aren't hoisted, so variables are parsed where they are declared

An example:

var firstName = "Brandon";

function ShowName()
{
	let lastName = "Bruno";
}

firstName is available everywhere, including the ShowName() function. lastName is only available inside ShowName().

Const

The const keyword is very similar to constants in other languages: these variables are immutable once declared. For example:

const middleName = "Michael";

Important takeaways:

  • let maintains tighter variable scope and is preferred over var in most situations
  • const declares immutable variables; useful for keys/settings/static content

Template literals

Template literals operate much like string interpolation in C#. JavaScript strings are denoted with single (') or double (") quotes, with no special meaning between either. Template literals are strings denoted with the backtick character (`) and allow variables and expressions to be tokenized directly in the string.

Including variables and expressions in strings typically requires concatenation:

let userBadge = "Full Name: " + firstName + " " + lastName;

Result: Full Name: Brandon Bruno

Using template literals:

let userBadge = `Address: ${streetNumber}, ${city}`;

Result: Address: 123 Peachtree St, Atlanta

Expressions can also be evaluated in template literals:

user.BirthYear = 1984;
let userInfo = `Age: ${2021 - user.BirthYear} years old`;

Result: Age: 36 years old

Important takeaways:

  • Use template literals in place of string concatenation
  • Denote template literal strings with backticks (`)
  • Tokens use a dollar sign and curly braces inside the string (${})
  • Expressions can be evaluated inside template literals

Arrow functions

JavaScript functions are written with a simple four-part structure:

  • the function keyword
  • an identifier
  • a list of parameters
  • a body (code block)

For example:

function FormatFullName(firstName, lastName)
{
	return `${firstName} ${lastName}`;
}

Arrow functions provide a unique, concise syntax for writing functions. The above can be consolidated into:

let FormatFullName = (firstName, lastName) => `${firstName} ${lastName}`;

// Call function
FormatFullName("Brandon", "Bruno");

While some functions can be rewritten with the arrow syntax, it's important to understand that arrow functions are meant to be used where a short, single-line function is called for or when less ceremony potentially makes code easier to read and understand.

An example of a quick one-line function:

setTimeout( () => alert('Annoyed by this message?'), 1500);

And an example where less code adds to the readibilty:

let person = {
	FormatName: (first, last) => { return `${first} ${last}`; }
}

// Call function:
person.FormatName("Brandon", "Bruno");

Arrow functions have other limitations (see the MDN page), but they work great when the function body has relatively simple logic.

Next Up

The next article in this series will look at advanced JavaScript concepts such as including Promises, window.fetch(), JavaScript modules, and more.

Additional Resources

Do you have questions, comments, or corrections for this post? Find me on Twitter: @BrandonMBruno