CoursePart 1 — JavaScript for PlaywrightLesson 1.10
Lesson 1.10Part 1 — JavaScript for Playwright

Function declarations vs expressions

Packaging reusable steps into a named block of code.

Lesson 1.10of 24
Next

Step 1

The idea

01

Imagine you need to make a cup of tea. The steps are: boil water → add teabag → pour water → wait → remove teabag → add milk. You'll do this every morning.

Instead of writing those steps out every time, you write them once and give them a name: makeTeа(). Then whenever you want tea, you just call that name.

That's a function. It's a named, reusable block of code. You define it once, call it whenever you need it.

Step 2

See it run

02
Output
Test started: Login Flow
Test PASSED
---
Test started: Checkout Flow
Test FAILED
---
Test started: Search Flow
Test PASSED
functions.js
// Define the function once
function runTest(testName, passed) {
  console.log(`Test started: ${testName}`);
  if (passed) {
    console.log("Test PASSED");
  } else {
    console.log("Test FAILED");
  }
  console.log("---");
}

// Call it as many times as needed
runTest("Login Flow", true);
runTest("Checkout Flow", false);
runTest("Search Flow", true);
Terminal
$ node functions.js

The words inside the parentheses — testName and passed — are parameters. They're slots that get filled with real values each time the function is called.

Step 3

Now you try

03

Define a function called greetTester that takes a name parameter and prints: Welcome to the team, [name]!

Call it three times with different names. Then add a second parameter role and update the message to: Welcome, [name] — role: [role]

💡Tip
If your function has a typo in the name when calling it, JavaScript says "is not a function". That error message always means: check your spelling.

Step 4

Why a tester cares

04

Functions let you write logic once and reuse it everywhere. Here's a tax calculator — one function, called many times with different inputs:

tax.js
function calculateTax(price, taxRate) {
  const tax = price * (taxRate / 100);
  const total = price + tax;
  return { price, tax, total };
}

function printBill(item, price, taxRate) {
  const bill = calculateTax(price, taxRate);
  console.log(`${item}: ₹${bill.price} + ₹${bill.tax.toFixed(2)} tax = ₹${bill.total.toFixed(2)}`);
}

printBill("Laptop",   45000, 18);
printBill("Notebook",   120, 12);
printBill("Pen",         15,  5);
Terminal
$ node tax.js
Output
Laptop: ₹45000 + ₹8100.00 tax = ₹53100.00
Notebook: ₹120 + ₹14.40 tax = ₹134.40
Pen: ₹15 + ₹0.75 tax = ₹15.75

If the tax formula ever changes, you update one function — all three bills update automatically. This is why functions are the most important concept in programming.

Recap

3 key points
  • 1A function is a named block of reusable code: function name(params) { ... }
  • 2Parameters are slots filled with real values each time the function is called.
  • 3Functions eliminate repetition — define once, use everywhere.