JavaScript Arrow Functions: Syntax, Implicit Return and this

Arrow functions (=>) are the short way to write a function, and they are everywhere in modern JavaScript and in every Playwright test: test("login", async ({ page }) => { ... }). In this lesson you will learn the arrow syntax in all its forms, the implicit return and its object trap, why arrow functions are perfect for callbacks, how they handle this differently, and when you should still use a regular function.

Advertisement

📖 What You’ll Learn: arrow function syntax, parameters with and without parentheses, implicit versus block body returns, returning object literals, arrow functions as callbacks, async arrow functions, lexical this, no arguments object, no new, differences from regular functions, and when not to use arrows.


➡️ Arrow Function Syntax

Definition: an arrow function is a compact function expression written with =>. It is always anonymous, so you usually store it in a variable or pass it directly as an argument.

📄 syntax.js

// Regular function expression
const addRegular = function (a, b) {
  return a + b;
};

// Arrow function with a block body
const addArrow = (a, b) => {
  return a + b;
};

// Arrow function with an implicit return
const add = (a, b) => a + b;

console.log(addRegular(2, 3), addArrow(2, 3), add(2, 3));

⌨️ Terminal

node syntax.js

🖥️ Output

5 5 5
FormExample
No parameters() => "ready"
One parameter (parentheses optional)n => n * 2 or (n) => n * 2
Several parameters(a, b) => a + b
Block body(a, b) => { const s = a + b; return s; }
Return an object(name) => ({ name, active: true })
Asyncasync (url) => await fetch(url)

💡 Tip: Prettier adds parentheses around a single parameter by default ((n) => ...). It looks consistent and makes adding a second parameter easier, so this course uses that style.


↩️ Implicit Return vs Block Body

If the part after => is an expression, its value is returned automatically (an implicit return). If it is a block in braces, you must write return yourself:

📄 implicit.js

const double = (n) => n * 2;              // implicit return
const doubleBlock = (n) => { n * 2; };     // block without return: returns undefined
const doubleFixed = (n) => { return n * 2; };

console.log(double(4), doubleBlock(4), doubleFixed(4));

⌨️ Terminal

node implicit.js

🖥️ Output

8 undefined 8

The object-literal trap

Braces after => always start a block, never an object. To return an object with an implicit return, wrap it in parentheses:

📄 object-return.js

const makeUserWrong = (name) => { name: name };      // a block with a label!
const makeUser = (name) => ({ name: name, role: "tester" });

console.log(makeUserWrong("Asha"));
console.log(makeUser("Asha"));

⌨️ Terminal

node object-return.js

🖥️ Output

undefined
{ name: 'Asha', role: 'tester' }

In the first version, name: is read as a statement label inside a block, so the function returns undefined without any error. This is one of the most common arrow function bugs.


Advertisement

🔁 Arrow Functions as Callbacks

Arrow functions shine when you pass a small function to another function, such as array methods, timers and event handlers:

📄 callbacks.js

const results = [
  { test: "login", status: "passed", ms: 820 },
  { test: "search", status: "failed", ms: 1430 },
  { test: "cart", status: "passed", ms: 610 },
];

const names = results.map((r) => r.test);
const failed = results.filter((r) => r.status === "failed");
const totalMs = results.reduce((sum, r) => sum + r.ms, 0);
const sorted = [...results].sort((a, b) => a.ms - b.ms).map((r) => `${r.test}:${r.ms}`);

console.log(names);
console.log(failed.map((r) => r.test));
console.log(totalMs);
console.log(sorted);

setTimeout(() => console.log("timer done"), 0);

⌨️ Terminal

node callbacks.js

🖥️ Output

[ 'login', 'search', 'cart' ]
[ 'search' ]
2860
[ 'cart:610', 'login:820', 'search:1430' ]
timer done

Compare the same filter call written with a regular function: results.filter(function (r) { return r.status === "failed"; }). The arrow version says the same thing in a third of the space.


⏳ Async Arrow Functions

Put async before the parameters to create an async arrow function. This is exactly the form Playwright tests use:

📄 example.spec.js (Playwright, for reference)

import { test, expect } from "@playwright/test";

test("home page has a title", async ({ page }) => {
  await page.goto("https://sqatools.in/");
  await expect(page).toHaveTitle(/SQA Tools/);
});

Here async ({ page }) => { ... } is an async arrow function whose single parameter is destructured to get page. A runnable Node.js example:

📄 async-arrow.js

const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

const runStep = async (name, ms) => {
  await wait(ms);
  return `${name} done after ${ms} ms`;
};

const main = async () => {
  console.log(await runStep("login", 20));
  console.log(await runStep("search", 10));
};

main();

⌨️ Terminal

node async-arrow.js

🖥️ Output

login done after 20 ms
search done after 10 ms

Promises and async/await are explained fully in Module 10.


🎯 Arrow Functions and this

The biggest technical difference: an arrow function has no this of its own. It uses the this of the code around it where it was written (this is called lexical this). A regular function gets its this from how it is called.

📄 this.js

const suite = {
  name: "Checkout",
  tests: ["add item", "pay"],

  printRegular() {
    this.tests.forEach(function (t) {
      // a regular callback has its own this (not suite), so this.name is undefined
      console.log(`${this?.name} > ${t}`);
    });
  },

  printArrow() {
    this.tests.forEach((t) => {
      // the arrow uses printArrow's this, which is suite
      console.log(`${this.name} > ${t}`);
    });
  },
};

suite.printRegular();
suite.printArrow();

⌨️ Terminal

node this.js

🖥️ Output

undefined > add item
undefined > pay
Checkout > add item
Checkout > pay

This makes arrow functions ideal for callbacks inside methods. But it also means an arrow function should not be used as an object method that needs this:

📄 method.js

const page = {
  url: "/login",
  openArrow: () => `opening ${this.url}`,     // this is not page here
  open() {
    return `opening ${this.url}`;             // method shorthand: this is page
  },
};

console.log(page.openArrow());
console.log(page.open());

⌨️ Terminal

node method.js

🖥️ Output

opening undefined
opening /login

In the arrow version, this comes from the surrounding module code, where it does not refer to page, so this.url is undefined. The this, call, apply and bind lesson explains the rules in full.


Advertisement

⚖️ Arrow vs Regular Functions

FeatureRegular functionArrow function
Syntaxfunction (a) { return a; }(a) => a
Own thisYes (depends on the call)No (lexical)
arguments objectYesNo
Can be used with newYesNo (TypeError)
Hoisted (declaration form)YesNo
Implicit returnNoYes, for expression bodies

📄 differences.js

function regular() {
  return arguments.length;
}
const arrow = (...args) => args.length;   // use rest parameters instead of arguments

console.log(regular(1, 2, 3), arrow(1, 2, 3));

const Person = (name) => { this.name = name; };
try {
  new Person("Asha");
} catch (e) {
  console.log(e.constructor.name + ":", e.message);
}

⌨️ Terminal

node differences.js

🖥️ Output

3 3
TypeError: Person is not a constructor

🚫 When Not to Use Arrow Functions

  • Object methods that use this: use method shorthand open() { ... }.
  • Constructors: use a class (arrows cannot be called with new).
  • DOM event handlers that rely on this being the element: use a regular function, or read event.currentTarget.
  • Top-level named helpers you want to call before their definition: a function declaration is hoisted and appears with its name in stack traces.

Everywhere else, especially short callbacks, arrow functions are the modern default.


🧪 Tester Scenario: Build a Mini Report with Arrow Functions

📄 report.js

const runs = [
  { suite: "smoke", passed: 12, failed: 0, ms: 41000 },
  { suite: "cart", passed: 18, failed: 2, ms: 98000 },
  { suite: "api", passed: 40, failed: 1, ms: 22000 },
];

const total = (r) => r.passed + r.failed;
const rate = (r) => ((r.passed / total(r)) * 100).toFixed(1) + "%";
const seconds = (ms) => (ms / 1000).toFixed(0) + "s";
const icon = (r) => (r.failed === 0 ? "✅" : "❌");

const lines = runs
  .map((r) => `${icon(r)} ${r.suite.padEnd(6)} ${rate(r).padStart(6)}  ${seconds(r.ms)}`)
  .join("\n");

console.log(lines);
console.log("suites with failures:", runs.filter((r) => r.failed > 0).map((r) => r.suite).join(", "));

⌨️ Terminal

node report.js

🖥️ Output

✅ smoke  100.0%  41s
❌ cart    90.0%  98s
❌ api     97.6%  22s
suites with failures: cart, api

Each arrow function does one small, named job, and map/filter combine them. This style is common in custom Playwright reporters and CI summary scripts.


Advertisement

📝 Practice Questions with Answers

Try each question on your own first, then open the answer to check your work. Run the code with node practice.js.

Q1. Rewrite as an arrow function with an implicit return.

function square(n) {
  return n * n;
}
Show answer

📄 practice1.js

const square = (n) => n * n;
console.log(square(9));

🖥️ Output

81

Q2. Write an arrow function toUser(name, email) that returns { name, email, active: true } using an implicit return.

Show answer

📄 practice2.js

const toUser = (name, email) => ({ name, email, active: true });
console.log(toUser("Asha", "asha@sqatools.in"));

🖥️ Output

{ name: 'Asha', email: 'asha@sqatools.in', active: true }

The parentheses around the object are required; { name, email } is shorthand for { name: name, email: email }.

Q3. Use map with an arrow function to convert [10, 25, 40] rupee prices to strings like "₹10.00".

Show answer

📄 practice3.js

const prices = [10, 25, 40];
console.log(prices.map((p) => `₹${p.toFixed(2)}`));

🖥️ Output

[ '₹10.00', '₹25.00', '₹40.00' ]

Q4. Find the bug: this function returns undefined.

const isAdult = (age) => {
  age >= 18;
};
Show answer

The braces create a block body, so the comparison is calculated but not returned. Remove the braces or add return:

📄 practice4.js

const isAdult = (age) => age >= 18;
console.log(isAdult(20), isAdult(15));

🖥️ Output

true false

Q5. Use filter and map with arrow functions to get the names of tests slower than 1000 ms from [{ name: "a", ms: 400 }, { name: "b", ms: 1500 }, { name: "c", ms: 2200 }].

Show answer

📄 practice5.js

const tests = [{ name: "a", ms: 400 }, { name: "b", ms: 1500 }, { name: "c", ms: 2200 }];
const slow = tests.filter((t) => t.ms > 1000).map((t) => t.name);
console.log(slow);

🖥️ Output

[ 'b', 'c' ]

Q6. This object method prints undefined. Fix it so it prints Base URL: https://qa.example.com.

const env = {
  baseURL: "https://qa.example.com",
  show: () => console.log("Base URL: " + this.baseURL),
};
env.show();
Show answer

Arrow functions do not get this from the object. Use method shorthand:

📄 practice6.js

const env = {
  baseURL: "https://qa.example.com",
  show() {
    console.log("Base URL: " + this.baseURL);
  },
};
env.show();

🖥️ Output

Base URL: https://qa.example.com

🧠 MCQ Quiz: Arrow Functions

10 questions on this lesson. Pick one answer for each, then press Check answers to see your score and an explanation for every question.

  1. What does const f = (n) => n + 1; return for f(4)?
  2. What does const f = (n) => { n + 1; }; return for f(4)?
  3. How do you return an object literal with an implicit return?
  4. Where does an arrow function get its this?
  5. What happens with new ((x) => x)()?
  6. Which is valid arrow syntax for a function with no parameters?
  7. Do arrow functions have an arguments object?
  8. Why is an arrow function a poor choice for an object method that uses this?
  9. Which signature is used for a Playwright test body?
  10. Why are arrow functions good callbacks inside class methods?

💼 Interview Questions and Answers

Q1. What are the differences between arrow functions and regular functions?

  • Arrow functions have lexical this; regular functions get this from the call site.
  • Arrow functions have no arguments object, no prototype, and cannot be called with new.
  • Arrow functions support an implicit return for expression bodies.
  • Arrow functions are always expressions, so they are not hoisted like function declarations.

Q2. Explain this output.

📄 counter.js

const counter = {
  count: 0,
  incArrow: () => { this.count++; return this.count; },
  inc() { this.count++; return this.count; },
};

console.log(counter.inc(), counter.inc());
console.log(counter.incArrow());
console.log(counter.count);

⌨️ Terminal

node counter.js

🖥️ Output

1 2
NaN
2

inc is a method, so this is counter and the count goes 1, 2. incArrow takes this from the module scope, where it is an empty object (module.exports in CommonJS), so this.count++ works on undefined and gives NaN, while counter.count stays 2.

Q3. Why does items.map(i => { id: i }) produce an array of undefined?

The braces are parsed as a function body, and id: as a label before the expression i. The body has no return, so every call returns undefined. Wrap the object in parentheses: items.map((i) => ({ id: i })).

Q4. When would you still use a regular function instead of an arrow function?

For object methods and class methods that use this (method syntax), for constructors (use class), for DOM handlers that rely on this being the element, for generator functions (function*, which have no arrow form), and for named top-level functions where hoisting and clear stack-trace names help.


Advertisement

❓ Frequently Asked Questions

🤔 When were arrow functions added to JavaScript?

In ES2015 (ES6). They work in every modern browser and every supported Node.js version.

🤔 Are arrow functions faster than regular functions?

Not in a way that matters. Choose them for brevity and lexical this, not for speed.

🤔 Can arrow functions be async?

Yes: const load = async () => { await ... }. This is the form used for Playwright test bodies and hooks.

🤔 Should single parameters have parentheses?

It is optional (n => n * 2 is valid). Many teams, and Prettier by default, always add them for consistency.


🏁 Summary

  • Arrow functions use (params) => expression or (params) => { statements }.
  • An expression body returns its value implicitly; a block body needs return; wrap returned objects in parentheses.
  • Arrow functions are ideal for callbacks (map, filter, timers) and async test bodies.
  • They have lexical this, no arguments, and cannot be used with new.
  • Use method shorthand for object methods that need this, and classes for constructors.

Next, continue with Lesson 19: Default, Rest and Spread Parameters.

🎬 Watch JavaScript and automation tutorials on YouTube!

Subscribe to SqaToolsByDY • Practice on sqatools.in