25 min·beginner

Lesson 1

How JavaScript runs

Build a practical mental model for how javascript runs and use it in working JavaScript.

By the end, you will be able to…

  • Explain how javascript runs in your own words
  • Use how javascript runs in a small program
  • Recognize and debug a common failure mode

Build the mental model

A JavaScript engine reads your file top to bottom, then executes it one statement at a time on a single call stack. Every function call is pushed onto that stack and popped off when it returns, which is why one script can never run two statements literally simultaneously.

main()
calculateOrder()
applyTax()

Newest call on top · pops off when it returns

The call stack

Syntax and working example

Read the code from inputs to output. Predict what it prints, then run it and change one value.

Working example
Expected output: Hello

Why this matters

Once you can see the call stack in your head, confusing stack traces, recursion limits, and 'why did this run before that' questions stop being mysterious.

Real-world example

Browser DevTools' Call Stack panel during a paused breakpoint is this exact model made visible.

Common mistakes

  • Assuming two functions run 'at the same time' because they're both called quickly
  • Not reading the error stack trace from the top down
  • Confusing 'the code that defines a function' with 'the code that calls it'

Try it yourself

Challenge

Add a second function that calls greet() and returns a longer sentence, then log the result.

Practice

Knowledge check

What does the JavaScript engine use to track which function is currently running?

Summary

JavaScript executes synchronously on one call stack: one frame at a time, pushed on call and popped on return.