Playwright + JS · Lesson 4 of 35

0/35 done

Module 4: JavaScript ES6+

4. Modern ES6+ Features & Modular JavaScript

13 minlesson

Try it yourself

Implement getSafeTimeout:

  1. Accept config object.
  2. Return config?.timeouts?.action ?? 5000.

The editor has a worked example. Read it, tweak it, then press Mark as complete.

Optional Chaining & Nullish Coalescing

Avoid "Cannot read properties of undefined" errors when parsing deeply nested test configs or API responses:

javascript
const response = {
  data: {
    user: {
      profile: { name: "Alice" }
    }
  }
};

// Safe access with ?.:
const avatarUrl = response?.data?.user?.profile?.avatar ?? "default-avatar.png";

// Nullish coalescing (??) only replaces null or undefined (not 0 or false):
const timeout = customConfig.timeout ?? 30000;

ES Modules (import / export)

javascript
// utils/locatorHelpers.js
export const getRowSelector = (id) => `tr[data-id="${id}"]`;

// In test file:
import { getRowSelector } from "../utils/locatorHelpers.js";

Key Takeaways & Walkthrough Summary

ES6 and modern ECMAScript standards make JavaScript expressive and resilient. In this lesson, we will explore optional chaining, nullish coalescing, and ES modules with import and export to organize your automation codebase. Let's explore!

Part of the Playwright + JS course (Playwright with JavaScript). Practice this concept live in the Playwright Online Compiler or explore our free automation practice form.

Common Doubts & Lesson Q&A

What is the difference between || and ?? in JavaScript?

|| treats 0, '', and false as falsy and replaces them. ?? only replaces null or undefined, preserving valid values like timeout = 0.

Finished reading?

Review the worked example in the editor, then mark the lesson complete.

JavaScript
Skip