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.
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.
You write source code. It is just text. On its own it does nothing.
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 value | 8 | 4 | 2 | 1 | Total |
|---|---|---|---|---|---|
0101 | 0 | 4 | 0 | 1 | 5 |
1101 | 8 | 4 | 0 | 1 | 13 |
1111 | 8 | 4 | 2 | 1 | 15 |
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:
Press Run (⌘ Enter) to see what happens.What does this print?
print(int("1010", 2))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.
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.
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:
C: the compiler turns the whole program into machine code once, ahead of time. You ship the executable.
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.
Press Run (⌘ Enter) to see what happens.main.py?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.
Press Run (⌘ Enter) to see what happens.What does this print?
console.log(0.5 + 0.25 === 0.75)
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:
| Language | What the build produces | What runs it | Machine code is made |
|---|---|---|---|
| C, C++, Rust, Go | A native executable for one OS and CPU | The CPU directly | Ahead of time, by the compiler |
| Python (CPython) | Nothing you ship; .pyc bytecode is cached in __pycache__ | The CPython virtual machine | Never for your code, by default; the VM is already machine code |
| Java, Kotlin | .class bytecode, bundled into .jar files | The JVM (Java virtual machine) | At run time, by the JVM's JIT, for hot methods |
| C#, F# | IL bytecode in .dll files | The .NET runtime | At run time by a JIT, or ahead of time with Native AOT |
| JavaScript | Your source, often bundled and minified | An engine: V8, SpiderMonkey, JavaScriptCore | At run time, by the engine's JIT, for hot functions |
| TypeScript | JavaScript, with the types removed | Whatever runs the JavaScript | Same as JavaScript |
| WebAssembly | A .wasm file of portable bytecode, compiled from C, C++, Rust or Go | A browser or a Wasm runtime | When 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 what you ship to what it is.
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 containsPython can tell you too. Run this here, then on your own machine:
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 CPUOr 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.
exec format error. What is the most likely cause?What "runtime" means
The word runtime has two meanings, and you will hear both:
- When the program is running, as opposed to when it is being written or compiled. "That bug only shows up at runtime."
- 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.
| Browser | Node.js | |
|---|---|---|
| Engine | V8, SpiderMonkey or JavaScriptCore | V8 |
| Job | Run code inside a web page | Run code on a computer or server |
| Has | document, window, localStorage | process, fs (files), http |
| Does not have | Direct access to your files | A 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 each piece to what it is.
node app.js and get ReferenceError: document is not defined. Why?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:
Press Run (⌘ Enter) to see what happens.basket is a name in the module's frame. The list itself lives on the heap.
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.
What does this print?
def reset(items):
items = []
items.append("x")
data = ["a", "b"]
reset(data)
print(data)- 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.