JavaScript basics
JavaScript is single-threaded: after the synchronous code, the whole microtask queue (promises, continuations after await) runs, then one macrotask. So a promise beats a zero-delay setTimeout, which explains some flaky tests. Pitfalls: == coerces types, fetch does not reject on 404 or 500 (check res.ok), forEach does not await async callbacks, and a missing await gives a falsely green test.
QA Fundamentals · Web and client-server
Why does code in setTimeout(…, 0) run after a promise, and '5' == 5 gives true?
An automated test in Playwright or Cypress is written in JavaScript or TypeScript. A bug with "desynchronisation" (the button is already there but the data has not come yet) is explained by events and queues. An error in the console shows up as a line of code you must be able to read. These are the reasons why QA needs not the whole language but its core: comparison, variables, asynchrony. This lesson covers exactly that and explains why JavaScript behaves this way and not another.
How it works and why. JavaScript is single-threaded: one piece of code runs at a time. So as not to block the page while waiting for the network or a timer, long operations are handed to the browser (Web APIs), and the result returns into a queue. There are two kinds of queues. Microtasks (promise callbacks, the continuation after await, queueMicrotask) and macrotasks (setTimeout, events, network callbacks). The order is this: all the synchronous code runs, then the microtask queue is emptied, then one macrotask is taken, and the cycle repeats (between them the browser may update the screen). So a promise created later fires before a timer with zero delay.
Execution order
Let us check on an example often given in interviews:
console.log('A');
setTimeout(() => console.log('B'), 0);
Promise.resolve().then(() => console.log('C'));
console.log('D');
// prints: A D C B
First the synchronous code runs: A is printed, the timer is handed to the browser, the promise puts a callback into the microtask queue, D is printed. Then the microtask queue empties (C), and only then comes the turn of the timer's macrotask (B). For QA this is not academic curiosity: "the element has appeared but the callback has not run yet" and similar windows between events underlie many unstable tests.
The second core is comparison. == first coerces the types, and === compares without coercion, so in code === is used almost always:
'5' == 5 // true (type coercion)
'5' === 5 // false (types differ)
null == undefined // true
null === undefined // false
0 == '' // true
NaN === NaN // false
typeof null // 'object' (a historical quirk)
Variables. var has function scope and is hoisted with the value undefined, so it is hardly used. let and const have block scope; a let value can be reassigned, a const cannot. But const for an object or an array does not make it immutable: the contents can be changed, only the variable itself cannot be reassigned. So const user = {name: 'A'}; user.name = 'B' works, and user = {} gives an error.
Asynchrony. A promise has the states pending, fulfilled and rejected, and async/await is a more convenient notation over promises: await pauses the function until the result, and errors are caught by an ordinary try/catch. Everything after await runs as a microtask.
Example: a typical trap with fetch. A developer (or a test author) writes a request and reads the response at once:
// Before: a 500 is silently treated as data
const res = await fetch('/api/orders');
const orders = await res.json();
// After: fetch rejects only on a network failure, so check res.ok
const res = await fetch('/api/orders');
if (!res.ok) throw new Error('HTTP ' + res.status);
const orders = await res.json();
The mistake is that fetch rejects the promise only on a network failure. For a 404 or 500 response it returns a successful result with res.ok = false. Without a check the code either fails on res.json() with a confusing error (if the body is HTML) or takes the error body for data. For QA this is a hint during analysis: "Uncaught SyntaxError: Unexpected token <" in the console often means that HTML of an error came instead of JSON. The same subtlety is in a loop: items.forEach(async (x) => { await save(x); }) does not wait for completion, because forEach ignores the returned promises. The right way is for (const x of items) await save(x) or await Promise.all(items.map(save)). The same logic is in automated tests: a missed await before actions or checks gives a test that "passes" without waiting for the result.
Limits and alternatives. In Node.js (where Playwright tests run) the event loop is the same, but there are its own features: process.nextTick and setImmediate have their own order, and there is no DOM. TypeScript adds types, but only at compile time: at run time it is the same JavaScript, so a type error may not show up until a value arrives from the network. For an interview the depth depends on the role: in manual QA it is enough to be able to read code and the console and to explain why data has not appeared yet, while in automation the ability to predict the execution order and to write correct async code is expected. Other automation languages (Python, Java) do not remove the need to understand the front end: its code is JavaScript anyway.
Common mistakes.
- Using
==and being surprised by unobvious type coercion. - Thinking that
setTimeout(fn, 0)runs the function immediately and before promises. - Not checking
res.okafterfetchand taking a server error for success. - Using
asyncinsideforEachand expecting the loop to wait. - Missing
awaitin a test: the check runs before the action has finished.
Check yourself
In what order will the console print: console.log(1); setTimeout(() => console.log(2)); Promise.resolve().then(() => console.log(3)); (async () => { console.log(4); await null; console.log(5); })(); console.log(6);
Answer
1, 4, 6, 3, 5, 2. First all the synchronous code: 1, 4 (up to await the function runs synchronously), 6. Then the microtasks in the order they were queued: 3 and the continuation after await (5). At the end the timer macrotask: 2.
fetch returned 404. Will execution go into catch?
Answer
No. The fetch promise is rejected only on a network failure (or an abort). For 404 it completes successfully and res.ok is false. So the status is checked explicitly, and then either an error is thrown or the response is handled.
const user = {name: "A"}; user.name = "B"; and then user = {}. What happens on each line?
Answer
The second line works: const forbids reassigning the variable, not changing the contents of the object. The third line gives a TypeError (Assignment to constant variable), because it tries to reassign the variable itself.