Modern JavaScript

By Lucas Bittencourt · · Updated

Table of contents:

Falsy, Truthy & Nullish values

JavaScript implicitly converts values when they are in a boolean context (such as in conditional operations).

Falsy values

Falsy values, when implicitly converted, are equivalent to false:

  • false
  • "" (empty string, including '' and empty template literals)
  • 0, -0, 0n
  • null
  • undefined
  • NaN

Truthy values

Truthy values, when implicitly converted, are equivalent to true:

  • true
  • Any non-empty string (including "0" and "false")
  • Any number other than 0 (including negative and floating-point numbers)
  • Infinity, -Infinity
  • [] (Array, empty or non-empty)
  • {} (Object, empty or non-empty)

Nullish values

Nullish values are always falsy and there are two possible values:

  • null
  • undefined

Numeric separators

Numeric separators improve the readability of literal numbers by adding a visual separator between groups, using an underscore ( _ )

const oneMillion = 1_000_000; // 1000000
const oneBillion = 1_000_000_000; // 1000000000
const oneMillionFiftyCents = 1_000_000.5; // 1000000.5

Template literals

Template literals (or template strings) are a syntactic sugar to build strings.

Don't do this:

const fullname = "My name is " + username + " " + lastname;

Do this instead:

const fullname = `My name is ${username} ${lastname}`;

It's good practice to use template literals for concatenation and + for mathematical operations.

Shorthand property names

We can use a shorter syntax for property names in object literals to simplify object creation.

Don't do this:

const person = {
  username: username,
  lastname: lastname,
  getFullname: getFullname,
};

Do this instead:

const person = {
  username,
  lastname,
  getFullname,
};

Don't do this:

const person = {
  user.name,
};

This way will throw an Uncaught SyntaxError: Unexpected token '.'

Do this instead:

const person = {
  name: user.name,
};

Bonus:

const person = {
  fullname: "Lucas Bittencourt",
  getFullname() {
    return this.fullname;
  },
};

Learn more about it here

Logical operator AND

The logical operator AND ( && ) returns the right-hand value if the left-hand value is truthy. Otherwise, it returns the left-hand value.

console.log(false && "Lucas Bittencourt"); // false
console.log(undefined && "Lucas Bittencourt"); // undefined
console.log(null && "Lucas Bittencourt"); // null
console.log(NaN && "Lucas Bittencourt"); // NaN

console.log(true && "Lucas Bittencourt"); // Lucas Bittencourt
console.log(1 && "Lucas Bittencourt"); // Lucas Bittencourt

console.log(1 && true && "Lucas Bittencourt"); // Lucas Bittencourt
console.log(1 && false && "Lucas Bittencourt"); // false

JSX:

{
  hasMinimumAge && <SomeComponent />;
}

Be careful with numbers in JSX: {items.length && <List />} renders 0 when the list is empty. Use {items.length > 0 && <List />} instead.

Logical operator OR

The logical operator OR ( || ) returns the right-hand value if the left-hand value is falsy. Otherwise, it returns the left-hand value.

console.log(false || "Lucas Bittencourt"); // Lucas Bittencourt
console.log(undefined || "Lucas Bittencourt"); // Lucas Bittencourt
console.log(null || "Lucas Bittencourt"); // Lucas Bittencourt
console.log(NaN || "Lucas Bittencourt"); // Lucas Bittencourt

console.log(true || "Lucas Bittencourt"); // true
console.log(1 || "Lucas Bittencourt"); // 1

console.log(0 || false || "Lucas Bittencourt"); // Lucas Bittencourt
console.log(0 || true || "Lucas Bittencourt"); // true
console.log(1 || true || "Lucas Bittencourt"); // 1

Nullish Coalescing operator

The Nullish coalescing operator ( ?? ) returns the right-hand value if the left-hand value is nullish.

console.log("" ?? "Lucas Bittencourt"); // ""
console.log(0 ?? "Lucas Bittencourt"); // 0
console.log(true ?? "Lucas Bittencourt"); // true

console.log(null ?? "Lucas Bittencourt"); // Lucas Bittencourt
console.log(undefined ?? "Lucas Bittencourt"); // Lucas Bittencourt

console.log(undefined ?? null ?? "Lucas Bittencourt"); // Lucas Bittencourt
console.log(undefined ?? false ?? "Lucas Bittencourt"); // false

Prefer ?? over || for default values when 0, "" or false are valid values:

const timeout = options.timeout || 5_000; // 0 becomes 5000 (bug)
const timeout = options.timeout ?? 5_000; // 0 stays 0

Logical Assignment operator

We can assign values conditionally using logical operators.

AND equals (&&=)

Only evaluates the right operand and assigns to the left if the left operand is truthy.

Don't do this:

if (user.name) {
  user.name = user.name.trim();
}

Do this instead:

user.name &&= user.name.trim();

OR equals (||=)

Only evaluates the right operand and assigns to the left if the left operand is falsy.

Don't do this:

if (!options.title) {
  options.title = "Untitled";
}

Do this instead:

options.title ||= "Untitled";

Nullish Coalescing equals (??=)

Only evaluates the right operand and assigns to the left if the left operand is nullish.

Don't do this:

let cache = null;

function getCache() {
  if (cache === null || cache === undefined) {
    cache = new Map();
  }

  return cache;
}

Do this instead:

let cache = null;

function getCache() {
  cache ??= new Map();
  return cache;
}

The difference between ||= and ??=:

const options = { retries: 0 };

options.retries ||= 3; // 3, because 0 is falsy
options.retries ??= 3; // 0, because 0 is not nullish

Optional Chaining

Optional Chaining is a safe way to access object properties that may be nullish.

Don't do this:

console.log(object.nullishReference.name);

This can lead to a runtime error: Uncaught TypeError: Cannot read properties of undefined (reading 'name')

Do this instead:

console.log(object.nullishReference?.name);

We also can use optional chaining in conditionals.

if (object.nullishReference?.name) {
  console.log("Hello, world");
}

We also can use optional chaining in arrays.

console.log(userList?.[0]?.name);

We also can use optional chaining in functions.

getUserData?.();
getUserData?.()?.name;

We can combine it with the Nullish Coalescing operator to provide a default value.

const city = user.address?.city ?? "Unknown";

Destructuring assignment

The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables.

Don't do this:

const username = user.username;
const lastname = user.lastname;

Do this instead:

const { username, lastname } = user;

We can destructure from functions:

const { username, lastname } = getUser();

We can set a default value:

const { username = "Lucas", lastname } = user;

We can destructure nested objects:

const {
  username,
  lastname,
  information: { email, age },
} = user;

We can rename object properties when destructuring:

const { username: name } = user;

We can create another object using the rest operator when destructuring:

const { username, lastname, ...userInfo } = user;

We can destructure function parameters:

function getUsername({ name, lastname }) {
  return `${name} ${lastname}`;
}

Don't do this:

const user1 = userList[0];
const user2 = userList[1];

Do this instead:

const [user1, user2] = userList;

We can skip array elements when destructuring:

const [user1, user2, , user4] = userList;

We can destructure multidimensional arrays:

const [[a, , c], , [, h, i]] = myArray;

We can set a default value:

const [a = 1, b, c] = numberList;

We can destructure objects within arrays:

const [{ username, lastname }, user2] = userList;

We can destructure arrays as if they were objects:

const {
  0: user1,
  1: user2,
  2: { username, lastname },
} = userList;

We can create another array using the rest operator when destructuring:

const [user1, user2, ...moreUsers] = userList;

We can destructure function parameters:

function sumNumbers([a, b, c]) {
  return a + b + c;
}

We can swap variables without a temporary variable:

[a, b] = [b, a];

Spread operator

Spread operator "expands" an array or object into its elements.

const newUser = { ...user, age: 25 };

const newUserList = [...userList, newUser];

We can spread nested object elements:

const newUser = {
  ...user,
  information: {
    ...user.information,
    username: "Lucas",
  },
  age: 25,
};

We can spread array elements as function arguments:

const numbers = [5, 1, 8];

Math.max(...numbers); // 8

Spread only creates a shallow copy: nested objects are still shared with the original object. To create a deep copy, use structuredClone.

Rest operator

Rest operator collects multiple elements and "condenses" them into a single element.

const { username, lastname, ...otherInfo } = user;

const [a, b, c, ...otherNumbers] = numberList;

Rest parameters

Rest parameters provide a way to accept an indefinite number of arguments as an array (variadic functions).

function sum(...numbers) {
  return numbers.reduce((total, number) => total + number, 0);
}

sum(1, 2, 3); // 6

Prefer rest parameters over the old arguments object, which is not a real array and doesn't exist in arrow functions.

Default function parameters

We can define default function parameters for optional arguments.

function getUsername(username = "Lucas Bittencourt") {
  return username;
}

We can set an object as default parameter:

function getUsername(user = { username: "Lucas Bittencourt" }) {
  return user.username;
}

We can combine it with destructuring to create named options:

function createUser({ name, role = "user", active = true } = {}) {
  return { name, role, active };
}

createUser({ name: "Lucas" }); // { name: "Lucas", role: "user", active: true }

Arrow functions expressions

Arrow functions are compact functions.

const getUser = (username, lastname) => {
  return {
    username,
    lastname,
  };
};

When an arrow function has only one expression, we can omit the return keyword and the curly braces.

const getUsername = (username) => username.trim();

When returning a literal object, we need to ensure it is enclosed in parentheses:

const getUserInfo = (name) => ({
  name: name.trim(),
});

We can also return a literal array:

const getNumbers = () => [1, 2, 3];

We can have an asynchronous arrow function:

const getUser = async (id) => {
  const response = await fetch(`/api/users/${id}`);
  return response.json();
};

Arrow functions don't have their own this: they use the this of the place where they were created. That's why they are great for callbacks, but should not be used as object methods.

async/await

JavaScript async/await is syntactic sugar for promises.

Don't do this:

function fetchUser() {
  getUser().then((user) => console.log(user));
}

Do this instead:

async function fetchUser() {
  const user = await getUser();
  console.log(user);
}

top-level await

In ES modules (e.g. .mjs files, "type": "module" or <script type="module">), we can use await at the top level, without an async function.

const config = await fetch("/config.json").then((response) => response.json());

Running promises in parallel

Awaiting independent promises one by one runs them in sequence.

Don't do this:

// the second request only starts after the first one finishes
const user = await getUser();
const posts = await getPosts();

Do this instead:

// both requests run at the same time
const [user, posts] = await Promise.all([getUser(), getPosts()]);
  • Promise.all: rejects as soon as one promise rejects
  • Promise.allSettled: waits for all of them and returns the status of each one
  • Promise.race: settles with the first promise that settles
  • Promise.any: fulfills with the first promise that fulfills
const results = await Promise.allSettled([getUser(), getPosts()]);

for (const result of results) {
  if (result.status === "fulfilled") {
    console.log(result.value);
  } else {
    console.error(result.reason);
  }
}

Promise.withResolvers

Creates a promise and returns it together with its resolve and reject functions, useful to turn callback APIs into promises.

Don't do this:

let resolve, reject;

const promise = new Promise((res, rej) => {
  resolve = res;
  reject = rej;
});

Do this instead:

const { promise, resolve, reject } = Promise.withResolvers();

socket.once("ready", resolve);
socket.once("error", reject);

await promise;

try...catch...finally

The try...catch statement is comprised of a try block and either a catch block, a finally block, or both. The code in the try block is executed first, and if it throws an exception, the code in the catch block will be executed. The code in the finally block will always be executed before control flow exits the entire construct.

Don't do this:

function fetchUser() {
  getUser()
    .then((user) => console.log(user))
    .catch((error) => console.error(error))
    .finally(() => console.info("Finished!"));
}

Do this instead:

async function fetchUser() {
  try {
    const user = await getUser();
    console.info(user);
  } catch (error) {
    console.error(error);
  } finally {
    console.log("Finished!");
  }
}

If you don't need the error, you can omit it:

function parseJson(text) {
  try {
    return JSON.parse(text);
  } catch {
    return null;
  }
}

Error cause

When you catch an error and throw a new one, use the cause option to keep the original error.

async function getUser(id) {
  try {
    return await database.users.find(id);
  } catch (error) {
    throw new Error(`Failed to get user ${id}`, { cause: error });
  }
}

Array.prototype.at

at() returns the item at the given index, and accepts negative indexes to count from the end.

Don't do this:

const lastUser = userList[userList.length - 1];

Do this instead:

const lastUser = userList.at(-1);

findLast and findLastIndex

Like find and findIndex, but searching from the end of the array.

const numbers = [1, 2, 3, 4, 5];

numbers.findLast((number) => number % 2 === 0); // 4
numbers.findLastIndex((number) => number % 2 === 0); // 3

Immutable array methods

sort, reverse and splice mutate the original array, which causes bugs, for example, with React state. Their immutable versions return a new array and keep the original one untouched:

  • toSorted() instead of sort()
  • toReversed() instead of reverse()
  • toSpliced() instead of splice()
  • with(index, value) instead of array[index] = value

Don't do this:

const sortedUsers = [...users].sort((a, b) => a.name.localeCompare(b.name));

Do this instead:

const sortedUsers = users.toSorted((a, b) => a.name.localeCompare(b.name));
const numbers = [3, 1, 2];

numbers.toSorted(); // [1, 2, 3]
numbers.toReversed(); // [2, 1, 3]
numbers.toSpliced(0, 1); // [1, 2]
numbers.with(0, 10); // [10, 1, 2]

console.log(numbers); // [3, 1, 2], unchanged

Object.groupBy and Map.groupBy

Groups the items of an array (or any iterable) by the value returned by a callback.

Don't do this:

const usersByRole = users.reduce((groups, user) => {
  groups[user.role] ??= [];
  groups[user.role].push(user);
  return groups;
}, {});

Do this instead:

const usersByRole = Object.groupBy(users, (user) => user.role);
// { admin: [...], user: [...] }

Use Map.groupBy when the keys are not strings, such as objects or dates:

const usersByTeam = Map.groupBy(users, (user) => user.team);

usersByTeam.get(team); // users of that team

Set methods

Sets now have methods to combine and compare them:

const frontend = new Set(["Lucas", "Ana", "John"]);
const backend = new Set(["Lucas", "Mary"]);

frontend.union(backend); // Set { "Lucas", "Ana", "John", "Mary" }
frontend.intersection(backend); // Set { "Lucas" }
frontend.difference(backend); // Set { "Ana", "John" }
frontend.symmetricDifference(backend); // Set { "Ana", "John", "Mary" }

new Set(["Lucas"]).isSubsetOf(frontend); // true
frontend.isSupersetOf(new Set(["Ana"])); // true
frontend.isDisjointFrom(new Set(["Peter"])); // true

Remember: set.has() is much faster than array.includes() for large lists.

Iterator helpers

Iterators now have methods like map, filter, take, drop, flatMap, reduce, some, every, find and toArray. Unlike array methods, they are lazy: each item goes through the whole chain one at a time, without creating intermediate arrays, and the processing stops as soon as possible.

function* naturalNumbers() {
  let number = 1;

  while (true) {
    yield number++;
  }
}

const firstEvenSquares = naturalNumbers()
  .filter((number) => number % 2 === 0)
  .map((number) => number ** 2)
  .take(3)
  .toArray();

// [4, 16, 36], even with an infinite generator

They also work with Map and Set iterators:

const adminNames = usersById
  .values()
  .filter((user) => user.role === "admin")
  .map((user) => user.name)
  .toArray();

structuredClone

structuredClone creates a deep copy of a value. It's available in browsers, Node.js, Deno and Bun.

Don't do this:

const copy = JSON.parse(JSON.stringify(user));

It loses Date objects (they become strings), Map, Set, undefined values, and fails with circular references.

Do this instead:

const copy = structuredClone(user);

Functions and DOM nodes can't be cloned (it throws a DataCloneError), and class instances lose their prototype (they become plain objects).

Object.hasOwn

Checks if an object has a property of its own (not inherited).

Don't do this:

Object.prototype.hasOwnProperty.call(user, "name");

Do this instead:

Object.hasOwn(user, "name");

Private class fields

Class fields and methods starting with # are truly private: they can't be accessed outside of the class.

class Counter {
  #count = 0;

  increment() {
    this.#count++;
    return this.#count;
  }

  static create() {
    return new Counter();
  }
}

const counter = Counter.create();

counter.increment(); // 1
counter.#count; // SyntaxError: Private field '#count' must be declared in an enclosing class

Unlike TypeScript's private keyword, which only exists at compile time, # fields are private at runtime.