Skip to content

Lesson 2 of 18How software works

How Code Runs

Follow your code from text file to CPU, and know what compilers, interpreters, bytecode, JIT and runtimes do.

19 min read0/9 questions

When you press Run, a lot happens between your text and the result on screen. You do not need every detail to write code, but knowing the main layers explains a surprising number of everyday puzzles: why Python is slower than C, why 0.1 + 0.2 is not exactly 0.3 in JavaScript, and why document exists in the browser but not in Node.js. "Is Python compiled or interpreted?" is also a classic interview warm-up.

The machine underneath

A computer, stripped down, has three parts you need to know about:

  • The CPU (central processing unit) is the worker. It does one tiny thing at a time, very fast: add two numbers, compare two numbers, copy a value, jump to a different instruction. A modern CPU does billions of these per second, on each of several cores (independent workers on the same chip).
  • Memory (RAM) is the workbench. It holds the program that is running and the data it is working on. It is fast but forgets everything when the power goes off.
  • Storage (an SSD or hard drive) is the filing cabinet. Your files live there permanently, but reading from it is much slower than reading from memory.

The CPU only understands machine code: instructions written as numbers, specific to that kind of CPU. An Apple M-series chip (ARM) and most Windows laptops (x86-64) speak different machine code. Nobody writes machine code by hand any more. You write source code, text in a language like Python, and some program turns it into instructions the CPU can follow.

The layers under your code
  1. Your codemain.py, index.js: text you wrote
  2. Language runtimeCPython, or V8 inside Node.js or a browser
  3. Operating systemmacOS, Linux, Windows: files, memory, processes
  4. HardwareCPU, RAM, storage, network card

You write source code. It is just text. On its own it does nothing.

1/5
Quick check
You write a program that builds a big list of numbers, then the laptop loses power. Where was the list, and is it still there?
Need a nudge? A hint rules out a wrong answer.

Bits and bytes

Memory is made of billions of tiny switches that are either off or on. One switch is a bit: a 0 or a 1. Eight bits make a byte, which can hold 256 different patterns (2 × 2 × 2 × 2 × 2 × 2 × 2 × 2).

Counting in binary (base 2) works like counting in normal decimal (base 10), except each column is worth twice the one to its right instead of ten times.

Column value8421Total
010104015
1101840113
1111842115

Everything in a computer is bits in the end. Text is stored as numbers (the letter A is 65), colours are three numbers for red, green and blue, and your source code file is a list of bytes. Python can show you the bits:

Python
print(bin(13)) # 0b means "binary follows"print(format(13, "08b")) # padded to 8 bits, one byteprint(int("1101", 2)) # binary text back to a numberprint(ord("A"), chr(66)) # a letter is stored as a number
Output
Press Run (⌘ Enter) to see what happens.
Predict the outputPython

What does this print?

print(int("1010", 2))
Need a nudge? Hints walk you through it.

To turn a number into binary yourself, keep dividing by 2. Each remainder is one bit, from right to left. 13 ÷ 2 is 6 remainder 1, 6 ÷ 2 is 3 remainder 0, 3 ÷ 2 is 1 remainder 1, 1 ÷ 2 is 0 remainder 1. Read the remainders backwards: 1101.

ChallengeEasy

Count in binary

Computers store numbers as bits: ones and zeros. Write a function that turns a non-negative whole number into its binary digits, as a string.

5   →  "101"
13  →  "1101"
0   →  "0"

Try it by hand with the divide-by-two method from the lesson: keep dividing by 2, and the remainders (read backwards) are the bits. Built-ins like Python's bin() or JavaScript's toString(2) also work, but doing it by hand once is worth it.

def to_binary(n: int) -> str: # Divide by 2 repeatedly and collect the remainders. pass

Compiled vs interpreted

There are two classic ways to turn source code into something the CPU can run.

A compiler translates the whole program into machine code before it runs, and saves the result as an executable file. C, C++, Rust and Go work this way. Compiling takes time up front, but the result runs at full speed, and many mistakes are caught before the program ever starts.

An interpreter reads your program and carries out each instruction as it goes. There is no separate build step: you just run the file. That makes experimenting fast, but the interpreter does extra work on every line while the program runs, so it is slower.

In practice, most modern languages mix the two. Here is what Python and C actually do:

Two roads to the CPU
hello.c: C sourcehello.cC sourceCompiler: gcc / clangCompilergcc / clangExecutable: machine codeExecutablemachine codemain.py: Python sourcemain.pyPython sourceBytecode: __pycache__/*.pycBytecode__pycache__/*.pycPython VM: the interpreter loopPython VMthe interpreter loopCPU: runs machine codeCPUruns machine codecompileonceruncompileinterpretrun

C: the compiler turns the whole program into machine code once, ahead of time. You ship the executable.

1/5

You can see Python's bytecode with the built-in dis module ("disassemble"). Run this and look for an instruction that loads a and b (its name starts with LOAD_FAST), then BINARY_OP for the +, then RETURN_VALUE. The exact names shift a little between Python versions, but the idea stays the same: small steps for a simple machine.

Python
import dis def add(a, b): return a + b dis.dis(add)print(add(2, 3))
Output
Press Run (⌘ Enter) to see what happens.
Quick check
Which sentence best describes how CPython runs main.py?
Need a nudge? A hint rules out a wrong answer.

JavaScript engines and JIT

JavaScript is run by an engine. Chrome, Edge and Node.js use V8, Firefox uses SpiderMonkey, and Safari uses JavaScriptCore. Like Python, a modern engine first turns your code into bytecode and starts interpreting it immediately, so the page does not wait.

Then it gets clever. The engine watches which functions run over and over (the "hot" ones), and compiles those into real machine code while the program is running. This is called JIT compilation (just-in-time). You get a fast start from the interpreter and close-to-compiled speed for the code that matters. It is a big reason JavaScript is usually much faster than plain CPython.

The JIT makes guesses, for example "this function is always called with numbers". If you suddenly pass it a string, the engine throws the fast version away and falls back to the slow path. Code that keeps its types consistent stays fast.

Numbers in JavaScript are stored as 64-bit floating point values: binary fractions. Some decimal fractions, like 0.1, cannot be written exactly in binary (the same way 1/3 cannot be written exactly in decimal), so tiny errors appear.

JavaScript
console.log(0.1 + 0.2);console.log(0.1 + 0.2 === 0.3);console.log((0.1 + 0.2).toFixed(2));console.log(Number.MAX_SAFE_INTEGER);
Output
Press Run (⌘ Enter) to see what happens.
Predict the outputJavaScript

What does this print?

console.log(0.5 + 0.25 === 0.75)
Need a nudge? Hints walk you through it.

Compilers, interpreters and bytecode in one table

"Compiled vs interpreted" is really a spectrum. The useful questions are: what do you ship, what has to be installed on the machine that runs it, and when does the translation to machine code happen? Here are the languages you are most likely to meet at work:

LanguageWhat the build producesWhat runs itMachine code is made
C, C++, Rust, GoA native executable for one OS and CPUThe CPU directlyAhead of time, by the compiler
Python (CPython)Nothing you ship; .pyc bytecode is cached in __pycache__The CPython virtual machineNever for your code, by default; the VM is already machine code
Java, Kotlin.class bytecode, bundled into .jar filesThe JVM (Java virtual machine)At run time, by the JVM's JIT, for hot methods
C#, F#IL bytecode in .dll filesThe .NET runtimeAt run time by a JIT, or ahead of time with Native AOT
JavaScriptYour source, often bundled and minifiedAn engine: V8, SpiderMonkey, JavaScriptCoreAt run time, by the engine's JIT, for hot functions
TypeScriptJavaScript, with the types removedWhatever runs the JavaScriptSame as JavaScript
WebAssemblyA .wasm file of portable bytecode, compiled from C, C++, Rust or GoA browser or a Wasm runtimeWhen the module loads, by the browser

A few things in that table are worth slowing down for.

Bytecode is everywhere. Python, Java, C# and JavaScript engines all use an in-between format. Bytecode is portable: the same .jar runs on a Mac and on a Linux server, because each machine has its own JVM that understands it. The price is that a virtual machine has to be installed, and something has to turn the bytecode into real CPU work.

The JVM looks a lot like V8. It starts by interpreting bytecode, watches which methods are hot, and JIT-compiles those. That is why a Java service is often slow for its first few seconds or minutes and then fast: it is warming up. Teams sometimes send fake traffic to a new instance before real users, for exactly this reason.

TypeScript is compiled, but only to JavaScript. Turning one high-level language into another is often called transpiling. The types are checked by tsc and then thrown away. Nothing checks them while the program runs, so a value from an API that does not match its declared type will not be caught by TypeScript at all. Recent Node.js versions can run a .ts file directly by stripping the types out, but they still do not type-check it; check the Node docs for what your version supports.

WebAssembly brings compiled languages to the browser. You compile C or Rust to .wasm once, and any modern browser can run it at close to native speed. The code windows on this site are an example: Pyodide is the CPython interpreter, written in C, compiled to WebAssembly. So when you run Python here, your browser runs a Wasm build of CPython, which runs your bytecode. Layers all the way down.

What the choice changes in practice:

  • Startup. Native executables start instantly. JIT runtimes start fast but take time to reach full speed. This matters for command-line tools and serverless functions that start cold on every request.
  • Shipping. A Go or Rust program is one file you copy to a server. A Python or Node.js app needs the right runtime version installed too, which is a big reason Docker images exist.
  • When errors appear. A compiler catches type errors and typos before the program runs. In Python and JavaScript, a typo in a branch that rarely runs can sit there for months, which is why tests and type checkers matter more in those languages.
Match the pairs0/5 matched

Match what you ship to what it is.

Choose an item, then its match on the other side.

Same code, different CPUs

Remember that machine code is specific to a kind of CPU. Two families matter at work: x86-64 (also written amd64 or x86_64), used by most servers and Windows laptops, and ARM64 (also aarch64 or arm64), used by Apple Silicon Macs, phones, and a growing share of cloud servers because they are cheaper to run. Check yours:

uname -m                      # arm64 on Apple Silicon, x86_64 on Intel and most serversfile "$(command -v python3)"  # which CPU types this executable contains

Python can tell you too. Run this here, then on your own machine:

Python
import platform, struct, sys print("CPU architecture:", platform.machine())print("Operating system:", sys.platform)print("Pointer size: ", struct.calcsize("P") * 8, "bits")print("Byte order: ", sys.byteorder)
Output
Press Run (⌘ Enter) to see what happens.

In this browser it prints something like wasm32 and emscripten: you are running inside WebAssembly, which looks like a small 32-bit machine to the code inside it. On a Mac with Apple Silicon the same lines print arm64 and darwin, with 64-bit pointers.

Interpreted code like your .py file does not care about any of this, because the interpreter handles the CPU. The trouble comes from compiled pieces: Python packages with C extensions (NumPy, database drivers, cryptography libraries), Node.js modules with native add-ons, and whole Docker images. A package installer downloads a prebuilt file for your CPU and OS. Copy that node_modules or virtual environment to a server with a different CPU and it breaks.

The classic version of this: you build a Docker image on an Apple Silicon Mac, push it, and the x86-64 server fails at startup with exec format error. The image is full of ARM machine code that the server's CPU cannot run. Fixes:

docker build --platform linux/amd64 -t myapp .   # build for the server's CPU

Or build multi-platform images that contain both, which docker buildx supports, or build in CI on the same kind of machine you deploy to. Always install dependencies inside the image during the build, never by copying them in from your laptop.

Quick check
Your Docker image works on your M-series Mac. On the company's x86-64 server it fails instantly with exec format error. What is the most likely cause?
Need a nudge? A hint rules out a wrong answer.

What "runtime" means

The word runtime has two meanings, and you will hear both:

  1. When the program is running, as opposed to when it is being written or compiled. "That bug only shows up at runtime."
  2. The environment that runs your code: the engine plus all the built-in tools it gives you.

The second meaning explains a common beginner confusion. JavaScript in the browser and JavaScript in Node.js use the same language and often the same engine (V8). But they come with different built-in objects, because they do different jobs.

BrowserNode.js
EngineV8, SpiderMonkey or JavaScriptCoreV8
JobRun code inside a web pageRun code on a computer or server
Hasdocument, window, localStorageprocess, fs (files), http
Does not haveDirect access to your filesA page, so no document

Python has runtimes too. CPython is the standard one, and the code windows on this site use Pyodide, which is CPython compiled to run inside a browser.

Match the pairs0/5 matched

Match each piece to what it is.

Choose an item, then its match on the other side.
Quick check
You run node app.js and get ReferenceError: document is not defined. Why?
Need a nudge? A hint rules out a wrong answer.

Memory: stack and heap, a first look

The workbench from the start of this lesson, RAM, is organised. Every running program splits its memory into two main areas, and you will hear both names in code reviews and interviews:

  • The stack holds function calls. Each call gets a frame: a small block with that call's local variables and where to go back to when it returns. Call a function and a frame is pushed on top; return and it is popped off. It is fast and tidies itself up, but it is small.
  • The heap holds everything that has to outlive one call or whose size is only known while the program runs: lists, dictionaries, strings, objects. It is large, and in Python and JavaScript a garbage collector frees heap objects once nothing refers to them.

In Python, the names in a frame do not hold the data. They refer to objects that live on the heap. Two names can refer to the same object, and passing a list to a function passes a reference, not a copy:

Python
def add_item(cart, item): cart.append(item) # changes the one list on the heap count = len(cart) # a local name in this call's frame return count basket = ["apple"]alias = basket # a second name for the same object n = add_item(alias, "pear")print(basket)print(n)print(alias is basket, id(alias) == id(basket)) copy = list(basket) # a new object on the heapcopy.append("plum")print(basket, copy)
Output
Press Run (⌘ Enter) to see what happens.
Names in frames, objects on the heap
NamesObjects in memorybasketlist['apple']

basket is a name in the module's frame. The list itself lives on the heap.

1/4

That one picture explains a whole family of bugs: a function that "secretly" changes its caller's list, a default argument that remembers values between calls, a copy that turns out not to be a copy. The Python course comes back to it many times.

What the Operating System Does opens up the rest: how each process gets its own private memory, why endless recursion overflows the stack, and what happens when the heap outgrows the machine's RAM. For now, keep the two-word version: frames on the stack, objects on the heap.

Predict the outputPython

What does this print?

def reset(items):
  items = []
  items.append("x")

data = ["a", "b"]
reset(data)
print(data)
Need a nudge? Hints walk you through it.
Key terms
machine code
Instructions as numbers that a specific kind of CPU executes directly.
compiler
A program that translates source code into another form (machine code or bytecode) before it runs.
interpreter
A program that executes code step by step while it runs, without producing a separate executable.
bytecode
Compact instructions for a virtual machine. CPython and JavaScript engines both use it.
JIT
Just-in-time compilation: turning frequently run code into machine code while the program is running.
runtime
The environment that runs your code, like Node.js or the browser. Also: the time when a program is running.
WebAssembly
A portable bytecode format that browsers compile to machine code, so C, Rust or Go can run on web pages.
architecture
The CPU family, like x86-64 or ARM64. Machine code built for one does not run on the other.
stack and heap
The stack holds one frame per active function call; the heap holds objects that outlive a call.