DEV Community

Cover image for From Classic to Cutting-Edge: The Ultimate Modern JavaScript Guide
Emmanuel Joseph
Emmanuel Joseph

Posted on

From Classic to Cutting-Edge: The Ultimate Modern JavaScript Guide


Modern JavaScript Cheatsheet

Introduction

Motivation

This document is a cheatsheet for JavaScript you will frequently encounter in modern projects and most contemporary sample code.

This guide is not intended to teach you JavaScript from the ground up but to help developers with basic knowledge who may struggle to get familiar with modern codebases (or, let's say, to learn React, for instance) because of the JavaScript concepts used.

Note: Most of the concepts introduced here are from a JavaScript language update (ES2015, often called ES6).

Table of Contents

  1. Modern JavaScript Cheatsheet
  2. Introduction
  3. Motivation
  4. Complementary Resources
  5. Table of Contents
  6. Notions
    • Variable Declaration: var, const, let
    • Arrow Function
    • Function Default Parameter Value
    • Destructuring Objects and Arrays
    • Array Methods - map / filter / reduce
    • Spread Operator "..."
    • Object Property Shorthand
    • Promises
    • Template Literals
    • Tagged Template Literals
    • Imports / Exports
    • JavaScript this
    • Class
    • Extends and super Keywords
    • Async Await
    • Truthy / Falsy
    • Anamorphisms / Catamorphisms
    • Generators
    • Static Methods
  7. Glossary
    • Scope
    • Variable Mutation

Notions

Variable Declaration: var, const, let

In JavaScript, there are three keywords available to declare a variable, and each has its differences: var, let, and const.

Short Explanation

Variables declared with the const keyword can't be reassigned, while let and var can.

I recommend always declaring your variables with const by default, but with let if it is a variable that you need to mutate or reassign later.

Keyword Scope Reassignable Mutable Temporal Dead Zone
const Block No Yes Yes
let Block Yes Yes Yes
var Function Yes Yes No

Sample Code

const person = "Nick";
person = "John"; // Will raise an error, person can't be reassigned

let person = "Nick";
person = "John";
console.log(person); // "John", reassignment is allowed with let
Enter fullscreen mode Exit fullscreen mode

Detailed Explanation

The scope of a variable roughly means "where is this variable available in the code".

var

Variables declared with var are function scoped, meaning that when a variable is created in a function, everything in that function can access that variable. Besides, a function-scoped variable created in a function can't be accessed outside this function.

Think of it as if an X scoped variable meant that this variable was a property of X.

function myFunction() {
  var myVar = "Nick";
  console.log(myVar); // "Nick" - myVar is accessible inside the function
}
console.log(myVar); // Throws a ReferenceError, myVar is not accessible outside the function.
Enter fullscreen mode Exit fullscreen mode

Here is a more subtle example:

function myFunction() {
  var myVar = "Nick";
  if (true) {
    var myVar = "John";
    console.log(myVar); // "John"
    // myVar being function scoped, we just erased the previous myVar value "Nick" for "John"
  }
  console.log(myVar); // "John" - see how the instructions in the if block affected this value
}
console.log(myVar); // Throws a ReferenceError, myVar is not accessible outside the function.
Enter fullscreen mode Exit fullscreen mode

Variables declared with var are moved to the top of the scope at execution. This is what we call var hoisting.

This portion of code:

console.log(myVar); // undefined -- no error raised
var myVar = 2;
Enter fullscreen mode Exit fullscreen mode

is understood at execution like:

var myVar;
console.log(myVar); // undefined -- no error raised
myVar = 2;
Enter fullscreen mode Exit fullscreen mode

let

Variables declared with let are:

  • Block scoped
  • Not accessible before they are assigned
  • Cannot be re-declared in the same scope

Let's see the impact of block-scoping with our previous example:

function myFunction() {
  let myVar = "Nick";
  if (true) {
    let myVar = "John";
    console.log(myVar); // "John"
    // myVar being block scoped, we just created a new variable myVar.
    // this variable is not accessible outside this block and totally independent
    // from the first myVar created!
  }
  console.log(myVar); // "Nick", see how the instructions in the if block DID NOT affect this value
}
console.log(myVar); // Throws a ReferenceError, myVar is not accessible outside the function.
Enter fullscreen mode Exit fullscreen mode

Temporal Dead Zone (TDZ)

Variables declared with let (and const) are not accessible before being assigned:

console.log(myVar); // raises a ReferenceError!
let myVar = 2;
Enter fullscreen mode Exit fullscreen mode

By contrast with var variables, if you try to read or write a let or const variable before they are assigned, an error will be raised. This phenomenon is often called the Temporal Dead Zone or TDZ.

Note: Technically, let and const variable declarations are hoisted too, but not their assignments. Since they can't be used before assignment, it intuitively feels like there is no hoisting.

In addition, you can't re-declare a let variable:

let myVar = 2;
let myVar = 3; // Raises a SyntaxError
Enter fullscreen mode Exit fullscreen mode

const

Variables declared with const behave like let variables but also cannot be reassigned.

To sum it up, const variables:

  • Are block scoped
  • Are not accessible before being assigned
  • Can't be re-declared in the same scope
  • Can't be reassigned
const myVar = "Nick";
myVar = "John"; // raises an error, reassignment is not allowed

const myVar = "Nick";
const myVar = "John"; // raises an error, re-declaration is not allowed
Enter fullscreen mode Exit fullscreen mode

Note: const variables are not immutable! This means that object and array const declared variables can be mutated.

For objects:

const person = { name: 'Nick' };
person.name = 'John'; // this will work! The person variable is not completely reassigned, but mutated
console.log(person.name); // "John"

person = "Sandra"; // raises an error, because reassignment is not allowed with const declared variables
Enter fullscreen mode Exit fullscreen mode

For arrays:

const person = [];
person.push('John'); // this will work! The person variable is not completely reassigned, but mutated
console.log(person[0]); // "John"

person = ["Nick"]; // raises an error, because reassignment is not allowed with const declared variables
Enter fullscreen mode Exit fullscreen mode

External Resources

  • How let and const are scoped in JavaScript - WesBos
  • Temporal Dead Zone (TDZ) Demystified

Arrow Function

The ES6 JavaScript update introduced arrow functions, which is another way to declare and use functions. Here are the benefits they bring:

  • More concise
  • this is picked up from surroundings
  • Implicit return

Sample Code

Concision and Implicit Return

function double(x) { return x * 2; } // Traditional way
console.log(double(2)); // 4

const double = x => x * 2; // Same function written as an arrow function with implicit return
console.log(double(2)); // 4
Enter fullscreen mode Exit fullscreen mode

this Reference

In an arrow function, this is equal to the this value of the enclosing execution context. Basically, with arrow functions, you don't have to do the "that = this" trick before calling a function inside a function anymore.

function myFunc() {
  this.myVar = 0;
  setTimeout(() => {
    this.myVar++;
    console.log(this.myVar); // 1
  }, 0);
}
Enter fullscreen mode Exit fullscreen mode

Detailed Explanation

Concision

Arrow functions are more concise than traditional functions in many ways. Let's review all the possible cases:

Implicit vs Explicit Return

An explicit return is a function where the return keyword is used in its body.

function double(x) {
  return x * 2; // this function explicitly returns x * 2, *return* keyword is used
}
Enter fullscreen mode Exit fullscreen mode

In the traditional way of writing functions, the return was always explicit. But with arrow functions, you can do an implicit return, which means you don't need to use the return keyword to return a value.

const double = (x) => {
  return x * 2; // Explicit return here
}
Enter fullscreen mode Exit fullscreen mode

Since this function only returns something (no instructions before the return keyword), we can do an implicit return.

const double = (x) => x * 2; // Correct, returns x*2
Enter fullscreen mode Exit fullscreen mode

To do so, we only need to remove the brackets and the return keyword. That's why it's called an implicit return; the return keyword is not there, but this function will indeed return x * 2.

Note: If your function does not return a value (with side effects), it doesn't do an explicit nor an implicit return.

If you want to implicitly return an object, you must have parentheses around it since it will conflict with the block braces:


javascript
const getPerson = () => ({ name: "Nick", age:
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
msc2020 profile image
msc2020

Good work!