Faragiri

Learn JavaScript Languages · JavaScript basics, The DOM, Async JavaScript and 2 more

Four lines that print out of order, three fetches that took 905 ms and then 301 ms, and the value that turns out to be a promise wearing a number's clothes.

5Branches
5Nodes below
3Depth

Recommended Before This

0 / 2

Golnaz is building a board that shows the level of three rivers, updating as the readings arrive. Four lines, and the order they print in is not the order they are written in.

  • console.log("1 read the gauge")
  • setTimeout(() => console.log("4 timer, next turn of the loop"), 0)
  • Promise.resolve().then(() => console.log("3 promise, end of this turn"))
  • console.log("2 draw the board")

They print 1, 2, 3, 4. A setTimeout of 0 runs after every line of synchronous code, not immediately, and a resolved promise runs at the end of the current turn, before any timer. Zero does not mean now; it means as soon as there is nothing else to do. Everything surprising about this language downstream of the syntax comes out of that one arrangement, and it is callbacks, promises and await.

The practical half is the cost of getting it wrong. Fetching three river levels, each taking about three tenths of a second: three awaits one after another took 905 ms and Promise.all took 301 ms, measured on 2026-09-01. await Promise.all([a, b, c]) starts all three and waits only for the slowest, and the sequential version was not doing more work, it was waiting three times for things that could have waited together.

The reason it can do that at all is the same arrangement: await does not block the thread, it hands control back to the loop, which is free to start the second request while the first is still in the air.

The parts that catch everyone once

Golnaz sorts the levels and gets them back wrong. [10, 9, 1].sort() returns [1, 10, 9] because the default sort compares as strings, and as strings "10" comes before "9". The fix is to say what the order is: [10, 9, 1].sort((a, b) => a - b) returns [1, 9, 10]. Nothing about this is a bug and it has been the defined behaviour since the beginning, which is the general shape of the surprises here.

Defined behaviour

What JavaScript does by default versus what you actually write

Neither surprise is a bug. Both have been part of the specification since the start, and each has a one-line habit that settles it.

Unqualified defaultConverts values before comparing
Explicit ruleCompares without guessing
[10, 9, 1] order[1, 10, 9] because default sort treats items as strings[1, 9, 10] with .sort((a, b) => a - b)
"2" against 2true under == after type conversionfalse under === with no conversion
[] against falsetrue under == even though [] is truthyfalse under === everywhere

Every linter written since 2010 enforces === by default, leaving numeric sort as the one you still have to remember yourself.

Interactive Practice Lab

Edit and run this snippet directly in your browser (zero setup)

JavaScript
const scores = [78, 92, 64, 95, 88];const passed = scores.filter((n) => n >= 70);const avg = passed.reduce((a, b) => a + b, 0) / passed.length;console.log('Passed count:', passed.length);console.log('Average score:', avg.toFixed(1));

Live Big-O Complexity & Binary Search Race Lab

Compare complexity curves at scale and watch Linear vs Binary Search race live.

The other is comparison. === compares without converting and == converts first, so "2" == 2 is true, and so is [] == false even though an empty array is itself truthy. The rule that survives is to use === everywhere and stop thinking about it, which is what every linter written since 2010 will insist on. These and the rest are types, functions and the parts that surprise people.

Overhead studio photograph on warm golden amber linen of three dark walnut blocks of mismatched heights placed out of size order beside a blurred brass rule.
JavaScript's default array sort compares items as text strings rather than numbers, one of several quirks that catch everyone until seen once.

Two places to run, and a smaller overlap than expected

The same file does not run in both places. document does not exist in Node and process does not exist in a browser, so a module that touches either is tied to one of the two. What is shared is larger than it was: fetch, URL, setTimeout and Promise are in both, which means most logic genuinely does move, and most of what does not move is the part that talks to the outside.

Where it runs

What moves between a browser tab and a server, and what does not

The shared part is larger than it was in 2015 and it is still not the part that talks to anything.

  • In a browser tab
  • In Node
fetch, URL, setTimeout, Promise
  • In a browser tabdocument, window, alert, and a person watching it happen
  • In Nodeprocess, Buffer, require, and a file system

Checked on Node 25 by asking for each name and seeing whether it was there. The overlap grows every year and the two lists on the outside have barely moved.

In the tab, the outside is the page itself. document.querySelector returns the first match and querySelectorAll returns all of them, and everything Golnaz's board does to the screen goes through those two and their neighbours, which is reading and changing the page from script. Splitting the code across files and getting it back into one thing the browser will load is splitting code up, and putting it back together.

Overhead photograph of two overlapping circular dark walnut trays on charcoal and ochre wool with one small polished brass ring resting right inside their narrow intersection.
Browsers and Node.js share the core JavaScript language inside a surprisingly small overlap while exposing completely different host APIs.

What to run in 2026

TypeScript is the one that changes the day. It is free and open source, it has been the default for new projects of any size since about 2019, and it replaced writing the types in a comment and hoping. It would have caught the sort above, and it catches the mistake in the next section outright, because a Promise and a number are different types and it says so before the page is loaded. What it is and what it does not catch is types on top of JavaScript, and what they catch.

What to run in 2026

Three free tools that replaced comments, browser-only scripts and style debates

Each layer solves one friction point before the page ever loads in a tab.

  1. PrettierRewrites layout automatically so code review stops arguing about whitespace.Formatting
  2. TypeScriptDefault for new projects since about 2019; catches a Promise passed where a number is expected before load.Type checking
  3. NodeRuns JavaScript outside the browser and powers the tooling that builds browser code.Server runtime

All three are free and open source, and together they explain why front-end tooling itself runs on JavaScript.

Node is the runtime outside the browser, free, and it replaced needing a browser to run any JavaScript at all, which is why the tooling for browser code is itself written in JavaScript. Prettier formats, and it replaced arguing about formatting in review.

The mistake: the value that is a promise wearing a value's clothes

This is the one that stops people, and it stops them because nothing breaks. Golnaz calls the function that fetches a level and forgets the await. The board prints Promise { <pending> }, which looks like an error and is not, and the arithmetic on it produces [object Promise]1 rather than 2.42. No exception, no stack trace, no line number.

One turn

Four states of Golnaz's board, in the order they actually happen

Each frame is a state of one thread, not a task somebody performs. Nothing here runs at the same time as anything else.

  1. 01The synchronous lines run to the endFirst turn. 1 read the gauge, then 2 draw the board. Nothing queued can interrupt this.
  2. 02The stack is emptyStill the first turn, and the only moment anything waiting is allowed to start.
  3. 03Promises drain firstEnd of the first turn. 3 promise, and every promise queued by that one too.
  4. 04Then a timerThe next turn. 4 timer, although it was written above the promise.

One thread throughout. Forgetting await leaves you holding the pending Promise from frame 3 instead of the resolved river level.

The rule that ends it: any function with async in front of it returns a promise, always, even when the body returns a number. Calling it gives you the promise; awaiting it gives you the number. When a value prints as Promise, the missing word is await, and it is missing on the line that produced the value rather than the line that printed it.

What this page has not touched is the half of the language that exists because a browser is a document viewer rather than a program viewer, and the frameworks built to stop hand writing that half: building an interface out of components, sitting on the structure under every page. The loop underneath all the ordering above is one queue and one thread, which is what happens between your file and the processor seen from the other side.

Low-key dark-oak photograph showing a sealed blank kraft claim envelope resting inside a small brass weighing pan directly beside an empty open wooden parcel box.
An unawaited Promise is only a pending claim ticket, not the delivered data inside: await it before reading or passing the result along.

Inside this, 5

Alongside this

Above this