Playwright + JS · Lesson 2 of 35

0/35 done

Module 2: Functions

2. Functions & Modern JavaScript Syntax

14 minlesson

Try it yourself

Implement buildTestUrl:

  1. Accept path string and optional baseUrl defaulting to "https://targetqa.com".
  2. Return ${baseUrl}${path}.

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

Functions & Arrow Functions in Test Automation

Arrow functions provide concise syntax and lexical this binding:

javascript
// Arrow function with default parameter:
const formatUrl = (path, host = "https://targetqa.com") => `${host}${path}`;

// Callback function pattern:
function executeWithRetry(action, retries = 3) {
  for (let i = 0; i < retries; i++) {
    try {
      return action();
    } catch (e) {
      if (i === retries - 1) throw e;
    }
  }
}

Destructuring & Rest/Spread

javascript
// Object destructuring:
const testConfig = { browser: "chromium", timeout: 30000, headless: true };
const { browser, timeout } = testConfig;

// Spread operator to clone and override options:
const mobileConfig = { ...testConfig, viewport: { width: 375, height: 667 } };

Key Takeaways & Walkthrough Summary

Functions are the core building blocks of reusable test automation. In this lesson, we will explore standard functions, arrow functions, callback patterns, template literals, and destructuring so you can write concise, readable test utilities. Let's dive in!

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

Why are arrow functions favored in Playwright test callbacks?

Playwright test runner blocks use arrow functions test('name', async ({ page }) => ...) for concise syntax and clean closure scoping.

Finished reading?

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

JavaScript
Skip