GinWorks Learn · free course
How Programming Works
The ideas behind every programming language, explained from zero. Run real code on every page, watch algorithms move, and predict what programs print. No installs, no sign-up.
- 9 chapters
- 47 lessons
- 23 runnable examples
- 38 visual labs
// chapters
Chapter 1 · Start
What programming is
A program is a list of precise instructions a computer follows. This chapter shows what that means, how a computer actually runs instructions, why everything inside it is numbers, and why there are so many programming languages.
// by the end you can
- Explain what a program is
- Describe how a processor runs instructions
- Read and write numbers in binary
- Explain why languages differ
- Tell compiled and interpreted languages apart
- 1.1What is a program?A program is a set of exact, step-by-step instructions that a computer follows, with no guessing and no common sense.
- 1.2How a computer runs instructionsA processor repeats one cycle billions of times a second: fetch the next instruction, work out what it means, do it.
- 1.3Why everything is numbersInside a computer, text, pictures, sound and programs are all stored as numbers, and those numbers are stored as patterns of 0s and 1s.
- 1.4Why there are so many languagesProgramming languages are tools for humans. They differ in what they're good at, how strict they are, and how close they sit to the hardware.
- 1.5Compiled and interpretedSome languages are translated into machine code before they run; others are read and run line by line by another program.
- 1.6Check: What programming isFive questions. Predict, then check.
Chapter 2 · Basics
The building blocks
Every program, in every language, is built from the same few pieces: values, the names we give them, and operations that combine them. Learn these and you can read most short programs.
// by the end you can
- Store and update values in variables
- Name the common data types
- Use arithmetic, comparison and text operators
- Work with text (strings)
- Write comments that help the next reader
- 2.1VariablesA variable is a name attached to a value, so you can store it, use it later and change it.
- 2.2Data typesValues come in kinds: whole numbers, decimals, text, true/false and "nothing". The type decides what you can do with a value.
- 2.3OperatorsOperators combine values: arithmetic to calculate, comparisons to ask questions, and logic to combine answers.
- 2.4Working with textStrings are sequences of characters. You can join them, measure them, cut pieces out and search inside them.
- 2.5Comments and readable codeCode is read far more often than it is written. Comments and good names are notes for the next person, often your future self.
- 2.6Check: The building blocksPredict what each snippet prints.
Chapter 3 · Control
Decisions and repetition
Programs become useful when they can choose what to do and repeat work without getting bored. Conditions and loops are how. Together with variables, they are enough to write almost any program.
// by the end you can
- Write if / else decisions
- Combine conditions with and, or, not
- Repeat work with for loops
- Use while loops safely
- Avoid infinite loops and off-by-one errors
- 3.1Making decisionsAn if statement checks whether something is true and runs different code depending on the answer.
- 3.2Combining conditions"And", "or" and "not" let one condition test several things. Truth tables show every possible case.
- 3.3Repeating with for loopsA for loop runs the same code a set number of times, or once for each item in a list.
- 3.4While loops and infinite loopsA while loop repeats as long as a condition stays true, which is handy when you don't know in advance how many rounds you need.
- 3.5Check: Decisions and repetitionPredict what each snippet prints.
Chapter 4 · Functions
Functions
A function packages a piece of work under a name, so you can reuse it, test it and think about it as one step. Functions are how small programs grow into big ones without turning into a tangle.
// by the end you can
- Write and call functions
- Pass inputs in and get results out
- Explain scope: where a name can be seen
- Follow a recursive function step by step
- 4.1Writing a functionA function is a named, reusable block of code. You define it once and call it whenever you need that job done.
- 4.2Inputs and outputsParameters are the inputs a function receives; return sends a result back to whoever called it.
- 4.3Scope: where names liveA variable created inside a function exists only inside it. This stops different parts of a program from trampling on each other.
- 4.4RecursionA recursive function solves a problem by calling itself on a smaller version of the same problem, until it reaches a case simple enough to answer directly.
- 4.5Check: FunctionsPredict what each snippet prints.
Chapter 5 · Data
Organising data
Real programs juggle lots of values: a shopping cart, a class register, a map of cities. Data structures are the containers that hold them. Picking the right one often makes the code shorter and faster.
// by the end you can
- Use lists (arrays) and their common operations
- Use dictionaries (objects) to look things up by name
- Explain stacks and queues
- Choose a structure to suit the job
- 5.1Lists (arrays)A list keeps values in order, numbered from 0. You can add, remove, read and loop over the items.
- 5.2Dictionaries (objects)A dictionary stores values under names (keys), so you can look something up directly instead of searching.
- 5.3Stacks and queuesA stack takes things off the top (last in, first out). A queue serves the one who waited longest (first in, first out).
- 5.4Choosing the right structureThe same data can be stored several ways. Ask how you'll use it most: in order, by name, newest first, or oldest first?
- 5.5Check: Organising dataPredict what each snippet prints.
Chapter 6 · Algorithms
Algorithms
An algorithm is a recipe for solving a problem. Two recipes can give the same answer but take wildly different amounts of time. This chapter shows searching, sorting, and how programmers describe speed.
// by the end you can
- Describe an algorithm in plain steps
- Compare linear and binary search
- Explain how a simple sort works
- Read Big O notation for common cases
- 6.1What is an algorithm?An algorithm is a finite, exact sequence of steps that solves a problem. It exists before any code; code is one way of writing it down.
- 6.2SearchingLinear search checks items one by one. Binary search, on sorted data, halves the remaining items with every check.
- 6.3SortingSorting puts items in order. Simple methods compare neighbours and swap; faster ones split the list and merge the pieces.
- 6.4How fast? Big OBig O describes how the work grows as the input grows. It ignores small details and asks: double the data, what happens to the time?
- 6.5Check: AlgorithmsFive questions on searching, sorting and speed.
Chapter 7 · Craft
Writing code that works
Professional programmers spend more time reading, fixing and checking code than writing new lines. This chapter covers the habits that make code trustworthy: reading errors, debugging, testing, and keeping history with version control.
// by the end you can
- Read an error message calmly
- Debug by narrowing down the problem
- Write simple automated tests
- Explain what version control and Git do
- 7.1Reading error messagesAn error message is the computer telling you exactly what confused it and where. Reading it carefully solves most problems.
- 7.2DebuggingDebugging is detective work: form a guess about what's wrong, test it, and narrow down until only the cause is left.
- 7.3TestingA test is a small piece of code that checks other code gives the right answer. Run tests every time you change something.
- 7.4Version control and GitVersion control records every change to your code, so you can go back in time, see who changed what, and work with others without overwriting each other.
- 7.5Check: Writing code that worksFive questions on errors, debugging and testing.
Chapter 8 · Software
How real software is built
Most software today runs across many computers: your phone, a web server, a database in a data centre. This chapter follows a request across the internet and introduces the pieces you hear about at work: front end, back end, databases, APIs and security.
// by the end you can
- Trace what happens when you open a web page
- Explain front end and back end
- Read a simple database query
- Explain what an API is
- Name the basic security habits every developer needs
- 8.1What happens when you open a websiteYour browser looks up the site's address, asks a server for the page, and builds what you see from the reply, usually in under a second.
- 8.2Front end and back endThe front end is what runs on your device and what you see. The back end runs on servers: it stores data, checks rules and does the heavy work.
- 8.3Databases and SQLA database stores data safely so many people and programs can use it at once. SQL is the long-standing language for asking it questions.
- 8.4APIsAn API is a menu of requests one program offers to others. It lets apps use maps, payments, weather or AI without building those themselves.
- 8.5Security basicsEvery program that touches the internet will be attacked eventually. A few habits prevent most of the common problems.
- 8.6Check: How real software is builtFive questions.
Chapter 9 · Next steps
Your path from here
You now know the ideas every language shares. This last chapter helps you pick a first language for your goals, use AI coding assistants wisely, and build the habits that turn a learner into a programmer.
// by the end you can
- Choose a language that fits your goal
- Use AI assistants without losing your own understanding
- Plan small projects that build real skill
- 9.1Choosing a first languageThere's no single best language. Pick one that fits what you want to build, learn it properly, and the next one comes much faster.
- 9.2Coding with AI assistantsAI tools can write, explain and fix code quickly. They're powerful helpers, but you still need to understand and check what they produce.
- 9.3How to keep learningProgrammers get good by building things slightly beyond their current skill, again and again. Small finished projects beat big unfinished ones.
- 9.4Check: Your path from hereFour quick questions.
Start · 1.1
What is a program?
A program is a set of exact, step-by-step instructions that a computer follows, with no guessing and no common sense.
On the team
Mateo Ruiz, 27, managed his mother Rosa's arepa shop in Bogotá for six years. Every evening, he copied the day's WhatsApp orders into a notebook by hand. In January 2026, he decided to learn to code and build a small ordering tool. His cousin Valentina, a back-end developer in Madrid, agreed to mentor him over video calls. Her first exercise was not on a computer at all. "Write the exact steps for taking an order," she said, "as if the reader has never seen an arepa." Mateo needed two pages.
The idea
A recipe says "add salt to taste". A person can handle that. A computer can't: it needs every step spelled out, in order, with nothing left to judgement. A program is exactly that kind of recipe, written in a language a computer can follow.
Programs are everywhere: the app on your phone, the lift in a building, the software that times traffic lights, the systems that move money between banks.
Example
Here is a whole program. Press Run. Then change the words and run it again.
The same program in Python:
print("Hello, world!")
print("I can count:", 2 + 3)Watch out
Computers do what you wrote, not what you meant. Most bugs are the gap between the two.
How it works
A program turns a task into steps that are small enough for a machine to do without judgement. The hard part isn't typing code; it's deciding exactly what the steps are.
- 1Understandwhat should happen, for whom, with what input
- 2Break it downinto small steps with no guessing
- 3Write itin a programming language
- 4Run itthe computer follows every step exactly
- 5Fix itcompare what happened with what you meant
This is why programmers spend so much time on edge cases. What if the customer orders zero arepas? What if two orders arrive at once? What if someone types "tres" instead of "3"? A person handles these without thinking; a program needs each one spelled out.
The skill that makes good programmers isn't speed at typing, but patience at breaking problems into pieces.
In the codebase
Most software is built by teams over years. The code you write will be read by others, changed and extended, so clarity matters from the first line.
Try it
Write the steps for making a cup of tea for someone who has never seen a kitchen. Then read them as a very literal robot would. Did you say which cupboard, how much water, or what to do if the kettle is already full? Every gap you find is a bug.
Remember
-
A program is a precise list of instructions.
-
Computers follow instructions exactly, with no common sense.
-
Programming is mostly breaking a problem into tiny, clear steps.
Start · 1.2
How a computer runs instructions
A processor repeats one cycle billions of times a second: fetch the next instruction, work out what it means, do it.
On the team
Mateo asked why his old laptop took ages to start a program that his phone opened in a second. Valentina explained that the phone's processor, though tiny, ran billions of simple steps every second on several cores at once, while the laptop was ten years old and mostly waiting for its slow hard disk. "Speed is about the processor, but also about how fast it can get to the data," she said.
The idea
At the heart of every computer is a processor (CPU). It has a tiny amount of very fast storage called registers and reads instructions from memory. It repeats one loop:
- Fetch the next instruction
- Decode what it means
- Execute it
- Move to the next one
Each instruction is very simple: add two numbers, copy a value, compare two values, jump to another instruction. Everything a computer does, from video calls to games, is built from millions of these small steps.
How it works
The processor is fast but forgetful: it can only work on what's in its registers. Everything else lives further away, and each step away is slower.
- Registersinside the processorfastest, tiny
- Cacheon the chipvery fast, small
- RAM (memory)the working space for running programsfast, cleared when power goes off
- SSD or diskstores files and programs permanentlymuch slower
- Networkother computersslowest of all
That's why programs load from disk into RAM before running, and why computers with more RAM can keep more programs open without slowing down.
Modern chips contain tens of billions of transistors. Several cores let a processor work on several instruction streams at once, which is why a phone can play music, download updates and run an app together.
In the codebase
Much of making software fast is about moving data less: keeping what you need close, and not fetching the same thing twice.
Try it
Open your computer's task manager (Ctrl+Shift+Esc on Windows, Activity Monitor on a Mac). Look at how much memory each program uses and how busy the processor is. Open a large web page and watch the numbers change.
You'll notice that a browser with many tabs often uses more memory than anything else, because each page keeps its own data, images and scripts in RAM. When memory runs out, the computer moves some data to the much slower disk, and everything starts to feel sluggish. That's the memory ladder in action, on your own machine.
Remember
-
The CPU loops: fetch, decode, execute.
-
Each instruction is tiny; power comes from speed and volume.
-
Memory holds both the instructions and the data.
Start · 1.3
Why everything is numbers
Inside a computer, text, pictures, sound and programs are all stored as numbers, and those numbers are stored as patterns of 0s and 1s.
On the team
Mateo's first order form showed customers' names as gibberish when they included ñ or accents: "Muñoz" instead of "Muñoz". Valentina laughed: "Everyone hits this once." The file had been saved in an old encoding and read as UTF-8. They switched everything to UTF-8, and Doña Rosa's customers got their names back.
The idea
Computer chips are made of billions of tiny switches that are either off or on. Off is 0 and on is 1. One 0-or-1 is a bit. Eight bits make a byte.
Counting in binary works like counting in ordinary numbers, except each place is worth twice the one to its right: 1, 2, 4, 8, 16, 32, 64, 128.
Example
-
The number 5 is
101in binary: 4 + 0 + 1. -
The letter "A" is stored as the number 65 using a shared code. Unicode is the worldwide standard that gives a number to over 150,000 characters, from Latin and Devanagari to Chinese, Arabic and emoji.
-
A pixel on your screen is three numbers: how much red, green and blue.
How it works
Everything a computer stores is a pattern of bits. What the pattern means depends on agreement: the same byte can be a number, a letter, part of a colour or part of an instruction.
Unicode 17, released in 2025, covers about 160,000 characters across the world's scripts, plus symbols and emoji. UTF-8 is the most common way to store them: it uses one byte for basic Latin letters and up to four for others, and it's the default on the web.
Garbled text, called mojibake, happens when bytes saved with one encoding are read as another. Using UTF-8 everywhere prevents most of it.
Try it
Count to ten in binary on paper: 1, 10, 11, 100, 101 and so on. Each new digit doubles what the number can hold. Then find the Unicode number for a letter in your own name using any online Unicode lookup.
One byte holds eight bits, enough for 256 different values, from 0 to 255. That's why colours on screens are often given as three numbers from 0 to 255: one byte each for red, green and blue. A kilobyte is about a thousand bytes, a megabyte about a million, and a gigabyte about a billion. A plain page of text is a few kilobytes; one phone photo is several megabytes.
Remember
-
A bit is a 0 or 1; a byte is 8 bits.
-
Each binary place is worth double the one before.
-
Unicode gives every character in every script a number.
Start · 1.4
Why there are so many languages
Programming languages are tools for humans. They differ in what they're good at, how strict they are, and how close they sit to the hardware.
On the team
Mateo asked Valentina which language he should learn. She asked what he wanted to build. A web page for orders meant JavaScript would run in customers' browsers. For the small server behind it, Python or JavaScript would both work. "Pick one, get good at it, and the second will take a fraction of the time," she said. He started with JavaScript and read Python alongside it.
The idea
A processor only understands machine code: raw numbers. Writing that by hand is slow and error-prone, so people invented languages closer to human thinking, and tools that translate them into machine code.
Languages sit on a ladder from close-to-the-machine to close-to-the-problem:
- Machine codenumbers the CPU runs directly
- Assemblyshort names for each machine instruction
- C, Rustfast, precise control over memory
- Java, Go, C#fast and safer, used for big systems
- Python, JavaScriptquick to write, huge libraries
How it works
Every language offers the same core ideas, such as variables, conditions, loops, functions and data structures, in different clothes. What differs is how they handle speed, safety and convenience.
The Stack Overflow Developer Survey 2025 found JavaScript was again the most used language among developers, with Python growing fastest in recent years, helped by AI and data work.
Popularity matters for beginners because popular languages have more tutorials, answered questions, libraries and jobs.
Try it
Visit a site like Rosetta Code, which shows the same small task solved in hundreds of languages. Pick one task, such as printing the numbers 1 to 10, and compare it in Python, JavaScript and C. Notice how the ideas are the same even when the words and symbols differ.
New languages keep appearing because needs change. Rust was designed for safety without losing speed. Kotlin made Android development friendlier. TypeScript added types to JavaScript for large projects. Most new languages borrow heavily from old ones, which is why learning a second language is so much faster than the first.
Remember
-
CPUs only run machine code; languages are for people.
-
Each language trades ease, speed and safety differently.
-
The core ideas carry over: learn one well and the next is much easier.
Start · 1.5
Compiled and interpreted
Some languages are translated into machine code before they run; others are read and run line by line by another program.
On the team
Valentina showed Mateo a bug in some Python code she maintained: a typo in a rarely used function that only crashed when a customer asked for a refund in a foreign currency, months after the code was written. In her Go code at work, the compiler would have caught a similar mistake before the program ever ran. "Each approach has trade-offs," she said. "Compilers catch some errors early; interpreters let you try ideas fast."
The idea
-
A compiler translates the whole program ahead of time into a file the computer can run. C, C++, Rust and Go work this way. Compiled programs usually run fast, and many mistakes are caught before the program ever runs.
-
An interpreter reads your program and carries it out as it goes. Python works this way. It's quick to try ideas, but some mistakes only show up when that line runs.
Many modern languages mix the two. Java and C# compile to an in-between form called bytecode. JavaScript engines in browsers compile the hot parts of your code just in time while it runs.
- Your code
- Compiler
- Machine code file
- Run
- Your code
- Interpreter reads and runs it, line by line
How it works
The difference is about when translation happens and what gets checked before running.
- translated before running
- many mistakes caught at compile time
- usually fast
- a build step between edit and run
- run straight from source
- quick to try ideas
- some mistakes only appear when that line runs
Most modern languages blur the line. Python compiles to bytecode behind the scenes. JavaScript engines use just-in-time (JIT) compilation, turning frequently used code into fast machine code while the program runs. Java and C# compile to bytecode that a virtual machine runs.
Type checkers and linters, such as TypeScript for JavaScript or mypy for Python, add some compile-time checking to interpreted languages, catching mistakes before they reach users.
In the codebase
Whatever the language, automated tests catch the mistakes the compiler can't.
Try it
In your browser's developer console (press F12), type 2 + 2 and press Enter. The browser's JavaScript engine runs it instantly, with no separate compile step you can see. That quick try-it loop is one reason interpreted languages are popular for learning.
Compiled programs are usually shipped as finished files for one kind of computer: a Windows program won't run on a Mac without being compiled again. Interpreted programs need the interpreter installed, but the same source code runs anywhere the interpreter does. Web browsers are the biggest example: the same JavaScript runs on billions of devices, from phones to laptops, because every browser includes an engine to run it.
Neither approach is better overall. Teams choose based on what matters most for the job: raw speed, quick changes, catching mistakes early, or running on many devices.
Remember
-
Compiled: translate first, then run.
-
Interpreted: translate while running.
-
Many languages blend both; the difference matters less than it used to.
Start · 1.6
Check: What programming is
Five questions. Predict, then check.
Basics · 2.1
Variables
A variable is a name attached to a value, so you can store it, use it later and change it.
On the team
Mateo's first order script used variables called a, b and c. A week later, he couldn't remember which was the price and which was the quantity. Valentina renamed them in front of him: arepasOrdered, pricePerArepa, orderTotal. "Now the code explains itself," she said. "Future-you is a different person who has forgotten everything."
The idea
Think of a variable as a labelled box. You put a value in, and refer to it by its label.
apples = 5
print(apples)
apples = apples + 3
print(apples)The = sign in most languages means "store this", not "is equal to". apples = apples + 3 would be nonsense in maths but makes perfect sense as an instruction.
Watch out
In JavaScript, const makes a name you can't reassign, and let makes one you can. Use const by default; it prevents accidental changes.
How it works
Under the hood, a variable is a name the program uses to find a value in memory. When you write apples = apples + 3, the computer reads the current value, adds 3, and stores the result back under the same name.
- 1Createlet total = 0a name and a starting value
- 2Readuse total in a calculation
- 3Updatetotal = total + 5read, calculate, store back
- 4Read againthe name now points to the new value
Names should say what the value means: deliveryFee beats df and x. Most languages have naming conventions, such as camelCase in JavaScript and snake_case in Python. Following them makes code familiar to other programmers.
Variables that can't be reassigned (const in JavaScript) are safer by default: if the value isn't supposed to change, the language will stop you changing it by accident.
In the codebase
Keep variables close to where they're used and give them the smallest job possible. A variable used in one place is easy to understand; one used everywhere is a source of bugs.
Try it
Open the browser console and type let cups = 2, then cups = cups + 1, then cups. You'll see 3. Try const tax = 0.19 and then tax = 0.2, and read the error: the language is protecting a value meant to stay fixed.
In many languages, variables that hold lists or objects store a reference, an address pointing to the data, rather than the data itself. Two variables can point to the same list, so changing it through one name changes what the other sees. This surprises almost every beginner once, and it's worth testing in the console to see it happen.
Remember
-
A variable is a name for a value.
-
=means "store", read right to left. -
Good names (
totalPrice, notx) make code readable.
Basics · 2.2
Data types
Values come in kinds: whole numbers, decimals, text, true/false and "nothing". The type decides what you can do with a value.
On the team
Mateo's order total came out as "25000025000" instead of 50000 pesos. Valentina spotted it instantly: the price from the web form arrived as text, "25000", and JavaScript joined two pieces of text instead of adding numbers. One Number() fixed it. "Data from users is always text until you check it," she said.
The idea
| Type | Examples | Used for |
|---|---|---|
| Number (integer) | 42, -7 |
Counting things |
| Number (decimal, "float") | 3.14, 0.1 |
Measurements, money calculations* |
| String (text) | "Lagos", 'こんにちは' |
Names, messages |
| Boolean | true, false |
Yes/no decisions |
| Nothing | null, None |
"No value here yet" |
*Real banking software stores money as whole cents or uses special decimal types, because decimals in binary can't be exact.
Example
Watch out
"5" (text) and 5 (a number) look the same to us but behave differently. Many bugs come from mixing them, especially with data typed in by users.
How it works
Types tell the computer how to read the bits in memory and which operations make sense. Adding two numbers, joining two strings, and asking whether something is true are different operations, and the type decides which one happens.
Languages differ in how strict they are. Some convert types automatically, which is convenient but surprising, such as JavaScript turning "5" + 5 into "55". Others refuse to mix types and raise an error, which feels strict but catches bugs early.
- JavaScript, PHP
- fast to write
- surprising results when types mix
- Python refuses "5" + 5
- TypeScript, Java, Rust check types before running
Decimals are stored in binary, which can't represent most decimal fractions exactly, just as 1/3 can't be written exactly in decimal. That's why 0.1 + 0.2 gives 0.30000000000000004, and why money is usually stored as whole cents or with special decimal types.
In the codebase
Convert and check input at the edges of your program, where data comes in, and trust the types inside.
Try it
In the browser console, type typeof 42, typeof "42", typeof true and typeof []. Then try "5" * 2 and "5" + 2, and notice the different results: JavaScript converts text to numbers for multiplication but joins strings for +.
Two special values cause many bugs: null and undefined in JavaScript, or None in Python. They mean "nothing here", and code that expects a real value often crashes when it meets one. Tony Hoare, who introduced null references in 1965, later called it his "billion-dollar mistake". Modern languages such as Kotlin, Swift and TypeScript in strict mode make you handle missing values explicitly, which prevents a whole class of crashes.
Remember
-
Every value has a type.
-
The type decides which operations make sense.
-
Decimals are approximate in binary; be careful with money.
Basics · 2.3
Operators
Operators combine values: arithmetic to calculate, comparisons to ask questions, and logic to combine answers.
On the team
Mateo needed to give every tenth order a free arepa. He was about to write a long chain of checks for orders 10, 20, 30 and so on, until Valentina showed him the remainder operator. If orderNumber % 10 === 0, it's a tenth order. One line replaced a page.
The idea
| Kind | Operators | Answer is |
|---|---|---|
| Arithmetic | + - * / % |
a number |
| Comparison | > < >= <= === !== |
true or false |
| Logic | && (and), || (or), ! (not) |
true or false |
Python writes the logic operators as the words and, or, not, and uses == for "equal".
How it works
Operators follow precedence rules, just like maths: multiplication before addition, comparisons before logic. Brackets override the order and make intention clear.
- Brackets( ) first
- Multiply, divide, remainder* / %
- Add and subtract+ -
- Comparisons> < >= <= === !==
- Logicnot (!), then and (&&), then or
The remainder operator % is surprisingly useful: checking even and odd numbers, cycling through colours, repeating something every n items, or converting minutes into hours and minutes.
In JavaScript, === checks both value and type, while == converts types first, which can give odd results. Most style guides say to use === always.
Try it
Predict, then check in the browser console: 7 % 3, 10 / 4, 2 + 3 * 4, (2 + 3) * 4, 5 == "5" and 5 === "5". Write your predictions down first. The ones you got wrong are the ones worth remembering.
Shortcut operators save typing: total += price means total = total + price, and count++ adds one. They're everywhere in real code, so it helps to read them fluently.
Division deserves care. In JavaScript, 10 / 4 gives 2.5, while Python offers both / for normal division and // for whole-number division. Dividing by zero gives Infinity in JavaScript but raises an error in Python. Integer overflow, when a number gets too big for its storage, has caused real disasters: in 1996, the Ariane 5 rocket was destroyed after a number too big for its slot crashed the guidance software.
Remember
-
%gives the remainder, useful for "every second item" or "is it even?". -
Comparisons always give true or false.
-
Brackets control the order, just like in maths.
Basics · 2.4
Working with text
Strings are sequences of characters. You can join them, measure them, cut pieces out and search inside them.
On the team
Customers typed their phone numbers every way imaginable: with spaces, dashes, brackets, a +57 country code, or none. Mateo's search for repeat customers kept missing people. Valentina showed him how to clean strings: remove everything that isn't a digit, then add the country code if it's missing. Suddenly, the system recognised regulars and Doña Rosa could greet them by name.
The idea
city = "São Paulo"
print(len(city))
print(city.upper())
print("Paulo" in city)
print(f"Welcome to {city}!")Watch out
Positions start at 0, not 1, in almost every language. The first character of city is city[0].
How it works
A string is a sequence of characters, each with a position starting at 0. Most languages treat strings as unchangeable: methods like toUpperCase() return a new string rather than changing the old one.
Cleaning, or normalising, input is one of the most common jobs in real programs: trimming spaces, making case consistent, removing punctuation from phone numbers, and checking formats such as emails and postcodes.
Comparing text from different languages has hidden traps: accented letters can be stored in more than one way in Unicode, and sorting order differs between languages. Libraries handle these properly.
In the codebase
Never build database queries or web pages by gluing user text into code. That's how injection attacks happen; part 8 explains.
Try it
In the console, set let name = " maría lópez ", then try name.trim(), name.toUpperCase(), name.length and name.split(" "). Notice the spaces and how each method returns a new string without changing the original.
Template strings make building messages much cleaner. Instead of "Hola " + name + ", your total is " + total, JavaScript lets you write `Hola ${name}, your total is ${total}`, and Python has f-strings that work the same way.
For finding patterns, such as every phone number or email in a block of text, programmers use regular expressions: a compact mini-language for describing text patterns. They're powerful but famously hard to read, so test them on real examples and leave a comment explaining what each one matches. Online testers show matches as you type.
When strings come from users, assume anything: empty input, emoji, very long text, other alphabets, or deliberate attempts to break your program.
Remember
-
Strings hold text in any script.
-
Templates (
${}in JavaScript, f-strings in Python) are the cleanest way to build messages. -
Counting starts at 0.
Basics · 2.5
Comments and readable code
Code is read far more often than it is written. Comments and good names are notes for the next person, often your future self.
On the team
Valentina showed Mateo a function she'd written five years earlier, with a single comment: "don't change this". Nobody on her team knew why. It took two days to discover that a payment provider required an odd rounding rule. She rewrote the comment to explain why, with a link to the provider's documentation. "Comments should answer the question the next person will ask," she said.
The idea
A comment is text the computer ignores. In JavaScript it starts with //; in Python, #.
How it works
Code tells you what happens. Good comments tell you why: the reason for a strange choice, a business rule, a link to documentation, or a warning about a trap.
- repeat the code
- out of date
- vague "fix this"
- commented-out old code left in
- explain why
- business rules and limits
- links to sources
- warnings about traps
The best way to reduce comments is clearer code: good names, small functions and simple logic often say what a comment would have said.
Tools called formatters, such as Prettier for JavaScript and Black for Python, automatically format code in a consistent style, so teams stop arguing about spaces and brackets.
In the codebase
Files that explain a whole project, such as a README, are just as important: how to install, run and test the code.
Try it
Find a short piece of code you wrote a while ago, or any example online. Delete every comment, then read it cold. Which parts confused you? Those are the places that needed a comment explaining why, or a clearer name.
Most languages also support documentation comments, written just above a function in a special format, such as JSDoc in JavaScript or docstrings in Python. Editors show these as tooltips when someone uses the function, and tools can turn them into documentation websites automatically.
Todo comments are useful while working, but they pile up. Many teams use a rule: every TODO must link to a ticket, or it gets fixed or deleted before the code is merged.
Linters, such as ESLint for JavaScript and Ruff for Python, go further than formatters: they flag likely bugs and risky patterns as you type, like unused variables or comparisons with ==.
Remember
-
Clear names beat clever comments.
-
Comment the why, not the what.
-
Consistent formatting makes code easier to scan.
Basics · 2.6
Check: The building blocks
Predict what each snippet prints.
Control · 3.1
Making decisions
An if statement checks whether something is true and runs different code depending on the answer.
On the team
Mateo's delivery fee rule was: free for orders over 60,000 pesos, 5,000 within the neighbourhood, 9,000 further away. His first version checked the neighbourhood before the order size, so big orders in the neighbourhood still paid a fee. Order of checks matters. He moved the "over 60,000" check first and the bug disappeared.
The idea
temperature = 31
if temperature > 30:
print("Hot: drink water")
elif temperature > 15:
print("Pleasant")
else:
print("Cold: take a jacket")The checks happen in order, and only the first one that's true runs.
Watch out
Python uses indentation (spaces at the start of a line) to group code. JavaScript uses { } braces. Get these wrong and the code does something different.
How it works
An if/else chain checks conditions from top to bottom and stops at the first true one. That makes the order of checks part of the logic: put the most specific or most important rules first.
- Order over 60,000?
- Yes: free delivery · No: in the neighbourhood?
- Yes: 5,000 · No: 9,000
Conditions compare values and produce true or false. Many languages also treat other values as "truthy" or "falsy" in conditions: in JavaScript, 0, empty strings, null and undefined all count as false, which is handy but can surprise you.
Long chains of conditions become hard to read. Common fixes are looking values up in a table, splitting the logic into small functions, or a switch or match statement for many fixed options.
In the codebase
Test every branch, including the "else" at the end. Bugs hide in branches that rarely run.
Try it
Write a condition chain for a cinema ticket: children under 12 pay half, people over 65 pay half, everyone else pays full price, and on Tuesdays everyone pays half. Test it with a 10-year-old on Tuesday, a 40-year-old on Monday and a 70-year-old on Tuesday. Does the order of checks change any result?
A useful habit is the early return, also called a guard clause. Instead of nesting conditions inside each other, check for problems first and leave the function straight away: if there are no items, return zero; if the customer is missing, return an error. The main logic then sits at the left edge, easy to read.
The ternary operator offers a one-line if/else for simple choices: const label = paid ? "Paid" : "Due";. It's neat for short decisions, but becomes hard to read when nested, so keep it simple.
Remember
-
ifruns code only when a condition is true. -
else if/elifadds more checks, tested in order. -
elsecatches everything left over.
Control · 3.2
Combining conditions
"And", "or" and "not" let one condition test several things. Truth tables show every possible case.
On the team
The arepa shop offered a lunch discount between 12 and 3, for students or anyone ordering over 30,000 pesos. Mateo's first version gave the discount at 9 pm to any student. He'd forgotten brackets: isLunch && isStudent || bigOrder read differently from what he meant. With brackets, isLunch && (isStudent || bigOrder), the rule matched the sign in the shop window.
The idea
A cinema lets you in if you have a ticket AND (are 18 or over OR are with an adult).
| A | B | A and B | A or B |
|---|---|---|---|
| true | true | true | true |
| true | false | false | true |
| false | true | false | true |
| false | false | false | false |
Watch out
"Or" in programming means at least one, so both being true still counts. In everyday speech, "tea or coffee?" usually means one, not both.
How it works
Logic operators combine true/false values. && (and) is true only if both sides are true; || (or) is true if at least one is; ! (not) flips the value.
Most languages also short-circuit: in a && b, if a is false, b is never checked, because the answer is already false. In a || b, if a is true, b is skipped. This lets you write safe checks such as user && user.name, which won't crash when there's no user.
De Morgan's laws help simplify conditions: "not (A and B)" is the same as "(not A) or (not B)".
In the codebase
Give complex conditions a name: const getsLunchDeal = isLunch && (isStudent || bigOrder); reads like the business rule.
Try it
Write out a truth table for a && !b: four rows, for every combination of a and b being true or false. Then check each row in the console. Truth tables are how programmers prove a tricky condition does exactly what it should.
Short-circuiting has a second everyday use: default values. In JavaScript, name || "guest" gives the name if there is one, or "guest" if it's empty. The newer ?? operator only falls back when the value is null or undefined, so a real zero or empty string is kept. That difference matters for things like a quantity of 0, which || would wrongly replace.
When a condition grows longer than a line, split it into named parts. A reviewer can check isOpen && hasStock && canDeliver far more easily than one long expression full of comparisons and brackets.
Remember
-
And: all must be true.
-
Or: at least one must be true.
-
Use brackets to make the order obvious.
Control · 3.3
Repeating with for loops
A for loop runs the same code a set number of times, or once for each item in a list.
On the team
At the end of each day, Mateo needed the total of all orders. With 3 orders, he could add them by hand in code. With 300, he needed a loop. "For each order in today's list, add its total to the sum," Valentina said, and wrote it in three lines. The same three lines worked on a busy Saturday with 450 orders.
The idea
total = 0
for i in range(1, 6):
total = total + i
print("i is", i, "total is", total)Read the JavaScript header as: start with i = 1; keep going while i <= 5; after each round, add 1 to i.
How it works
A for loop has three parts: a start, a condition to keep going, and a step after each round. The most common modern form loops directly over the items in a list, without counting.
- 1Startset up a counter or take the first item
- 2Checkis there more to do?
- 3Bodyrun the code for this item
- 4Stepmove to the next item
- 5Repeat or stopback to the check, or finish
In JavaScript, for (const order of orders) loops over each item; in Python, for order in orders: does the same. Most real code uses this form far more than counting with i.
Many languages also have built-in functions that hide the loop: map to transform every item, filter to keep some, and reduce or sum to combine them.
In the codebase
Loops over large data are where programs slow down. If a loop calls the database or the network each time round, it can be thousands of times slower than fetching everything once.
Try it
In the console, create a list: const prices = [12000, 8000, 15000]. Write a for...of loop that adds them up. Then try prices.reduce((a, b) => a + b, 0) and prices.map(p => p * 1.19) to see the same work done with built-in functions.
Loops can be nested: a loop inside a loop goes through every combination, such as every row and column of a table, or every pair of customers. Nested loops are natural for grids but can be slow on large data, a topic part 6 explores with Big-O.
Two keywords change a loop's flow: break stops the loop entirely, useful once you've found what you're looking for, and continue skips to the next item, useful for ignoring cancelled orders.
Off-by-one errors, looping one time too many or too few, are among the most common bugs. Looping directly over items avoids most of them.
Remember
-
Loops replace copy-and-paste.
-
The loop variable (often
i) changes each round. -
Looping over a list ("for each item") is the most common loop of all.
Control · 3.4
While loops and infinite loops
A while loop repeats as long as a condition stays true, which is handy when you don't know in advance how many rounds you need.
On the team
Mateo wrote a loop to keep asking for a phone number until the customer entered a valid one. In testing, he typed letters on purpose, and the program froze. The loop never changed what it checked: it asked once, then checked the same old answer forever. Valentina moved the "ask again" inside the loop. "Every loop needs a way out," she said.
The idea
How many years until savings double at 7% a year?
Watch out
If the condition never becomes false, the loop runs forever: an infinite loop. The program freezes. Always check that something inside the loop moves it towards the exit. (The runner on this page stops any code that runs longer than two seconds, so try it safely.)
Off-by-one errors are the other classic loop bug: running one time too many or too few, often from < versus <=.
How it works
A while loop checks its condition before each round. If the condition starts false, the body never runs at all. A do-while loop, available in some languages, runs the body once before the first check.
- 1Checkis the condition still true?
- 2Runthe body
- 3Change somethingthat moves towards the end
- 4Back to checkor stop
While loops suit situations where the number of rounds isn't known in advance: reading a file until it ends, retrying a network request until it works, or asking for input until it's valid.
To guard against infinite loops in real code, programmers often add a maximum number of tries, such as retrying a payment three times and then giving up with a clear error.
In the codebase
When a program freezes, an infinite loop is one of the first suspects. Logging inside the loop shows whether it's stuck.
Try it
Write a loop that starts with 1 and keeps doubling until the number passes 1,000. Print each value. How many rounds did it take? Now change the condition by mistake so it can never become false, and see how the browser warns you about a page that's stopped responding.
Games and apps run on a special kind of while loop called an event loop or game loop: keep going while the app is open, checking for clicks, keypresses and messages, updating, then drawing. Browsers run JavaScript this way, which is why one long-running loop in a web page can freeze everything: nothing else gets a turn until it finishes.
If you find yourself writing while (true), make sure a break inside the loop is guaranteed to run eventually.
Remember
-
whilerepeats as long as its condition is true. -
Something inside must change so the loop can end.
-
Test the first and last round when checking a loop.
Control · 3.5
Check: Decisions and repetition
Predict what each snippet prints.
Functions · 4.1
Writing a function
A function is a named, reusable block of code. You define it once and call it whenever you need that job done.
On the team
Mateo's code calculated the delivery fee in four different places: the order form, the receipt, the daily report and the WhatsApp message. When the fee changed, he updated three and forgot one, and some customers were charged the old price. Valentina helped him move the rule into one function, deliveryFee(order), called from all four places. The next fee change took one edit.
The idea
Without functions, you'd copy the same lines everywhere. With them, you write the job once:
def greet(name):
return "Hello, " + name + "!"
print(greet("Amara"))How it works
A function bundles steps behind a name. Calling it runs those steps, possibly with inputs, and gives back a result. Each call gets its own fresh set of local variables, so calls don't interfere with each other.
- Definefunction deliveryFee(order) { ... }
- CalldeliveryFee(todaysOrder)
- Runthe steps inside, with order = todaysOrder
- Returnthe fee comes back to where it was called
The principle Valentina used is often called DRY: don't repeat yourself. When a rule lives in one place, changing it is safe.
Good functions do one clear job, have a name that says what that job is, and are short enough to read in one go.
In the codebase
Large programs are mostly functions calling other functions. Learning to split work into well-named functions is one of the most important skills in programming.
Try it
Write a function called areaOfRoom(width, length) that returns the area. Call it for three rooms and add the results. Then change the function to round to one decimal place, and notice that every call benefits without changing anything else.
Functions can also be stored in variables and passed to other functions, just like numbers or strings. That's what happens when you give sort a comparison function, or tell a button which function to run when it's clicked. These passed-in functions are called callbacks, and they're everywhere in JavaScript.
Short arrow functions, such as x => x * 2, are handy for these small jobs.
When naming functions, start with a verb that says what they do: calculateTotal, sendReceipt, isOpenNow. Names starting with is, has or can are a common convention for functions that return true or false. A function that's hard to name is often doing too many things and is worth splitting.
Remember
-
Define once, call many times.
-
A good function does one clear job.
-
Its name should say what that job is (
calculateTax,sendReminder).
Functions · 4.2
Inputs and outputs
Parameters are the inputs a function receives; return sends a result back to whoever called it.
On the team
Mateo's first discount function printed the discounted price to the screen. It worked, until he needed the discounted price inside the receipt and the daily report. The function didn't give anything back. Valentina changed console.log(price) to return price, and now the result could be used anywhere: printed, saved, or added up.
The idea
-
Parameters (
width,length) are placeholders. -
Arguments (
3,4) are the actual values you pass in. -
returnends the function and hands back a value.
Watch out
Printing a value is not the same as returning it. console.log shows something on screen; return gives the value to the rest of your program so it can be used.
How it works
Parameters are the names a function uses for its inputs; arguments are the actual values you pass in when calling it. return sends a value back and ends the function immediately.
- shows a value on screen
- the caller can't use it
- good for messages
- sends the value back
- the caller can store, combine or print it
- good for calculations
Functions that only use their inputs to produce an output, without changing anything outside, are called pure functions. They're easy to test and reason about, because the same inputs always give the same output.
Many languages let you give parameters default values, such as function greet(name = "friend"), so callers can leave them out.
In the codebase
Keep functions to a few parameters. If you need many, group them into an object with named fields.
Try it
Write function discount(price, percent = 10) that returns the discounted price. Call it with one argument and with two. Then use the result twice: once in a printed message and once added to a running total. That second use is only possible because the function returns its answer.
A function can return only one value, but that value can be a list or an object holding several things, such as { total, tax, fee }. Many languages let you unpack these straight into separate variables.
Functions that change things outside themselves, such as saving to a database, sending a message or editing a global list, have side effects. Programs need side effects to be useful, but keeping them in a few clearly named places makes code much easier to test and debug.
A function with no return statement still returns something: undefined in JavaScript or None in Python. Forgetting return is a classic beginner bug.
Remember
-
Inputs go in as parameters.
-
One result comes back with
return. -
Functions that only depend on their inputs are the easiest to test.
Functions · 4.3
Scope: where names live
A variable created inside a function exists only inside it. This stops different parts of a program from trampling on each other.
On the team
Mateo's report showed the wrong total. He'd used a variable called total inside a function and another total outside it, and expected them to be the same. Valentina explained scope: the total inside the function was a separate variable that existed only while the function ran. "It's like two people called Ana in different rooms," she said.
The idea
Two variables can share a name if they live in different scopes. The local one hides the outer one while the function runs.
How it works
Scope decides where a name can be seen. Variables created inside a function or block live only there, and disappear when it finishes. Inner code can see names from outside it, but outer code can't see inside.
- Global scopevisible everywhereuse sparingly
- Function scopevisible inside one function
- Block scopevisible inside one { } block, for let and const in JavaScript
When inner code creates a variable with the same name as an outer one, the inner one hides, or shadows, the outer one inside that scope. That's what tripped Mateo up.
Global variables are risky because any part of the program can change them, making bugs hard to trace. Passing values into functions as parameters and returning results keeps data flow visible.
In the codebase
Keep scopes small: declare variables where they're first needed, not all at the top.
Try it
In the console, run let x = 1; { let x = 2; console.log(x); } console.log(x);. You'll see 2, then 1: the inner x lived only inside the braces. Then try the same with var instead of let, and notice the older keyword ignores block scope, which is one reason modern JavaScript avoids it.
Scope also explains closures: an inner function remembers the variables around it, even after the outer function has finished. A counter function that returns another function which adds one each time is the classic example. Closures power event handlers and many JavaScript patterns.
In Python, indentation shows blocks, but variables created inside an if or a loop are still visible in the rest of the function; only functions create a new scope. Each language has its own rules, so check them when you switch.
A practical rule for any language: if a variable is used by just one function, define it inside that function. The fewer places that can change a value, the fewer places a bug can hide, and the easier it is for others to understand your code.
Remember
-
Names created inside a function are local to it.
-
Prefer local variables; global ones can be changed from anywhere.
-
Pass values in as parameters instead of reaching outside.
Functions · 4.4
Recursion
A recursive function solves a problem by calling itself on a smaller version of the same problem, until it reaches a case simple enough to answer directly.
On the team
The shop's menu had categories inside categories: Arepas > Filled > Cheese > With extra cheese. Mateo wanted to count every item on the menu. Loops got messy because he didn't know how deep the nesting went. Valentina wrote a function that counts the items in a category and then calls itself for each subcategory. Five lines handled any depth.
The idea
5! ("five factorial") means 5 × 4 × 3 × 2 × 1. Notice that 5! = 5 × 4!, and 4! = 4 × 3!, and so on, down to 1! = 1.
Each call waits for the one it started. The computer tracks these waiting calls on the call stack.
Watch out
Forget the base case and the function calls itself forever until the stack runs out of room: a "stack overflow" error.
How it works
A recursive function solves a problem by solving smaller versions of the same problem. It needs two parts: a base case that stops, and a recursive case that moves towards it.
- 1Base casethe simplest version, answered directly
- 2Recursive casebreak into a smaller version of the same problem
- 3Call itselfon the smaller piece
- 4Combinethe answers on the way back up
Each call waits on a stack until the calls it made return. Without a base case, calls pile up until the program runs out of stack space and crashes with a "stack overflow".
Recursion fits naturally with nested structures: folders inside folders, menus inside menus, comments with replies, family trees and the structure of web pages.
In the codebase
Anything recursion can do, a loop with a stack can do too. Use whichever makes the code clearer.
Try it
Write a recursive function countdown(n) that prints n and calls countdown(n - 1), stopping at 0. Then remove the base case and run it: you'll see a "Maximum call stack size exceeded" error, the stack overflow in real life.
The classic example is factorial: 5! is 5 × 4 × 3 × 2 × 1. Recursively, the factorial of n is n times the factorial of n − 1, and the factorial of 1 is 1. Fibonacci numbers work similarly, but the simple recursive version recalculates the same values again and again, getting very slow. Storing answers you've already worked out, a technique called memoisation, makes it fast.
Some famous algorithms are recursive at heart: merge sort, quicksort and searching through folders all split the problem and call themselves on the pieces.
Remember
-
Recursion = a function calling itself on a smaller input.
-
Every recursive function needs a base case.
-
It suits naturally nested things: folders inside folders, family trees, menus.
Functions · 4.5
Check: Functions
Predict what each snippet prints.
Data · 5.1
Lists (arrays)
A list keeps values in order, numbered from 0. You can add, remove, read and loop over the items.
On the team
Mateo stored each day's orders in separate variables: order1, order2, order3. On a busy day, he ran out of names. Valentina showed him a list, or array: one name, orders, holding as many orders as needed, in arrival order. Adding an order became orders.push(newOrder); counting them became orders.length.
The idea
cart = ["rice", "lentils", "mangoes"]
print(cart[0])
cart.append("tea")
for item in cart:
print("-", item)How it works
A list keeps items in order and gives each a position, its index, starting at 0. Reading or changing an item by its index is very fast, because the computer can calculate exactly where it is in memory.
Adding or removing at the end is cheap. Adding or removing at the start or middle means shifting every item after it, which gets slow for very long lists.
Searching an unsorted list means checking items one by one. For frequent lookups by name or ID, a dictionary is usually better.
In the codebase
Most data your programs handle comes as lists: rows from a database, results from an API, lines in a file. Getting comfortable with map, filter and sort pays off quickly.
Try it
In the console, create const orders = ["cheese", "chicken", "beef"]. Try orders[0], orders.length, orders.push("veggie"), orders.includes("beef") and orders.indexOf("chicken"). Then try orders[10] and notice you get undefined rather than an error in JavaScript; Python would raise an IndexError instead.
Lists can hold other lists, which is how you represent a grid, like a seating plan or a spreadsheet: seats[2][5] means row 2, seat 5.
Be careful when changing a list while looping over it: removing items mid-loop can make the loop skip some. A safer approach is to build a new list with filter, keeping only the items you want.
Sorting a list changes it in place in JavaScript. If you need the original order later, copy it first with [...orders] or use the newer toSorted() method, which returns a sorted copy.
Tuples, in Python, are like lists that can't be changed once created. They suit fixed groups of values, such as a map coordinate or an RGB colour, and protect against accidental edits.
Remember
-
Lists keep order; positions start at 0.
-
push/appendadds to the end. -
Looping over a list is one of the most common things code does.
Data · 5.2
Dictionaries (objects)
A dictionary stores values under names (keys), so you can look something up directly instead of searching.
On the team
To look up a customer's last order by phone number, Mateo looped through every customer in a list. With 2,000 customers, it was noticeably slow on the shop's old tablet. Valentina switched to a dictionary keyed by phone number. Each lookup now went straight to the right customer, however many there were.
The idea
JavaScript calls these objects; Python calls them dictionaries; other languages say map or hash table. The idea is the same: key → value.
How it works
A dictionary, also called a map, hash map or object, stores key–value pairs. Behind the scenes, a hash function turns each key into a number that says where to store the value, so finding it again takes about the same time whether there are ten entries or ten million.
- items in order
- find by position
- searching means checking one by one
- items by key
- find by name or ID almost instantly
- keys must be unique
Keys must be unique: storing a second value under the same key replaces the first. Values can be anything, including lists and other dictionaries, which is how most real-world data is shaped.
JSON, the format most web APIs use to send data, is built from lists and dictionaries.
In the codebase
When you find yourself searching a list repeatedly by some ID, build a dictionary once and look up from that.
Try it
In the console, create const stock = { cheese: 12, chicken: 8 }. Read stock.cheese, set stock.beef = 5, and try Object.keys(stock) to list every key. Then read stock.ham and notice you get undefined: always check whether a key exists before trusting its value.
Counting things is a classic dictionary job. To count how often each arepa was ordered, loop through the orders and add one to counts[order] each time, starting from zero for new keys. The same pattern counts words in a text, visits per page, or votes per option.
Dictionaries can be nested: a customer record might hold a name, a phone number, and a list of past orders, each of which is itself a dictionary with an item, a date and a price. This shape is exactly what most APIs and document databases send back.
In JavaScript, the Map type is a dedicated dictionary that keeps keys in insertion order and allows any kind of key, including numbers and objects. Python's dict also keeps insertion order.
Remember
-
Keys are labels; values can be anything, even other lists or objects.
-
Looking up by key is very fast, even with millions of entries.
-
Most data on the web travels as JSON, which is just objects and lists written as text.
Data · 5.3
Stacks and queues
A stack takes things off the top (last in, first out). A queue serves the one who waited longest (first in, first out).
On the team
In the shop's kitchen, orders should be cooked in the order they arrived. Mateo's first version took the newest order first, so early customers waited longest. He'd built a stack, last in first out, when he needed a queue, first in first out. Changing pop() to shift() fixed it, and the lunch rush got fairer.
The idea
-
Stack: a pile of plates. The "Undo" button and the call stack from recursion both work this way.
-
Queue: a line at a bus stop. Print jobs and customer-support tickets work this way.
How it works
Stacks and queues are lists with rules about where items enter and leave.
- add and remove at the top
- undo history
- browser back button
- function calls
- add at the back, remove from the front
- kitchen orders
- print jobs
- messages waiting to be processed
Your program uses a stack constantly without you seeing it: the call stack keeps track of which function called which, so each one knows where to return. That's the stack that overflows when recursion never stops.
Queues are everywhere in large systems: messages, payments and emails are often placed in queues so that a busy moment doesn't overwhelm the system. Workers take items from the queue at a steady pace.
A priority queue adds a twist: items come out in order of importance rather than arrival, like an emergency room.
In the codebase
For large queues, use a proper queue structure or service. Removing from the front of a plain array gets slow as it grows.
Try it
In the console, make a stack: const s = []; s.push(1); s.push(2); s.push(3); s.pop();. You get 3, the last one added. Then make a queue: const q = []; q.push(1); q.push(2); q.push(3); q.shift();. You get 1, the first one added. Same list, different rules.
Stacks solve a famous puzzle: checking that brackets in code are balanced. Go through the text; push each opening bracket, and when you meet a closing one, pop and check it matches. If the stack is empty at the end, every bracket was closed. Code editors use the same idea to highlight matching brackets.
A deque, short for double-ended queue, lets you add and remove at both ends quickly. Python's collections.deque is the usual choice when you need a fast queue, since removing from the front of a normal Python list gets slower as the list grows. Browsers use a similar idea for their history: back and forward are two stacks, and visiting a new page clears the forward stack, which is why the forward button greys out.
Remember
-
Stack: last in, first out (LIFO).
-
Queue: first in, first out (FIFO).
-
Both are just lists with rules about where you add and remove.
Data · 5.4
Choosing the right structure
The same data can be stored several ways. Ask how you'll use it most: in order, by name, newest first, or oldest first?
On the team
Mateo's menu was a list of items, his customers a dictionary by phone number, and the kitchen orders a queue. When Valentina asked why, he could explain each one: order matters for the menu, fast lookup for customers, fairness for the kitchen. "That's the whole skill," she said. "The question is always: how will I use this data?"
The idea
| You need to… | Use |
|---|---|
| Keep things in order, loop through them | List / array |
| Look things up by a name or ID | Dictionary / object |
| Undo the latest action | Stack |
| Serve requests fairly, in arrival order | Queue |
| Check "have I seen this before?" quickly | Set |
| Represent roads between cities, friends of friends | Graph |
Example
A phone's contacts app keeps a dictionary from names to numbers for instant lookup, and a sorted list of names to show you on screen. Using two structures for two jobs is normal.
How it works
Choosing a data structure means matching it to the operations you'll do most often, because each structure makes some operations fast and others slow.
A set is like a dictionary with keys only. It answers "have I seen this before?" instantly and never holds duplicates: ideal for unique visitors or tags.
Getting the structure right often matters more for speed than clever code. A program that searches a list thousands of times can become instant by switching to a dictionary or set.
In the codebase
When data must survive after the program stops, it goes into a database, which builds its own structures, called indexes, for fast lookup.
Try it
For each of these, decide which structure you'd use: the songs in a playlist, the unique visitors to a website today, the product prices looked up by barcode, the support tickets waiting to be answered, and the steps of undo in a drawing app. Then check your answers against the guide above.
Real programs combine structures. An online shop might keep a dictionary of products keyed by ID, each product holding a list of photos and a set of tags, while orders wait in a queue for the warehouse. Thinking about the shape of your data before writing code saves a lot of rewriting later.
Trees and graphs are the next structures to learn. A tree has a root with branches, like folders on a computer or the structure of a web page. A graph connects items in any pattern, like friends on a social network or roads between towns, and powers maps, recommendations and route planners.
Remember
-
Start from how the data will be used.
-
Lists for order, dictionaries for lookup.
-
It's fine to keep the same data in more than one shape.
Data · 5.5
Check: Organising data
Predict what each snippet prints.
Algorithms · 6.1
What is an algorithm?
An algorithm is a finite, exact sequence of steps that solves a problem. It exists before any code; code is one way of writing it down.
On the team
Every morning, Doña Rosa planned the delivery route in her head. Mateo wanted to automate it. Valentina warned him: finding the very best route through many stops is a famously hard problem. Instead, they used a simple algorithm: from each stop, go to the nearest unvisited one. It wasn't perfect, but it was good enough, fast, and easy to explain to the delivery driver.
The idea
Finding the largest number in a list, in plain steps:
- Remember the first number as "biggest so far"
- Look at the next number
- If it's bigger, remember it instead
- Repeat until the end
- Answer: biggest so far
The word comes from the name of al-Khwārizmī, a 9th-century Persian mathematician in Baghdad whose books spread step-by-step methods for calculation.
How it works
An algorithm is a finite, exact procedure that turns input into output. Good algorithms are correct, finish in reasonable time, and are clear enough to check.
- 1Inputwhat do we start with?
- 2Outputwhat exactly do we want?
- 3Stepsa precise method, in order
- 4Checkdoes it work for normal, empty and extreme cases?
- 5Costhow does it slow down as input grows?
Some problems have fast exact algorithms; others, like finding the shortest route through many stops, called the travelling salesperson problem, have no known fast exact method for large inputs. In practice, programmers use heuristics: rules of thumb that give good answers quickly.
The word comes from the name of the 9th-century Persian mathematician Muhammad ibn Musa al-Khwarizmi, whose books spread step-by-step methods of calculation.
In the codebase
Most everyday programming uses well-known algorithms from libraries rather than inventing new ones.
Try it
Write an algorithm, in plain steps, for finding the tallest person in a room. Then test it on an imagined room with one person, with nobody, and with two people of equal height. Did your steps handle every case? Adjusting for those is exactly what programmers do.
Algorithms are judged on two main costs: time, meaning how many steps they take, and space, meaning how much memory they need. Often you can trade one for the other: storing results takes memory but saves recalculating them.
Many everyday algorithms follow a few big patterns. Divide and conquer splits a problem into halves, as binary search and merge sort do. Greedy algorithms take the best-looking choice at each step, like Mateo's nearest-stop route. Dynamic programming stores answers to small sub-problems and builds bigger answers from them, used in spell checkers and route planners.
Remember
-
An algorithm is exact, finite and solves a problem.
-
Write the steps in plain words first, then code them.
-
Good algorithms are correct first, fast second.
Algorithms · 6.2
Searching
Linear search checks items one by one. Binary search, on sorted data, halves the remaining items with every check.
On the team
Mateo's tablet searched 5,000 past orders one by one to find a customer's history. Valentina asked whether the orders were sorted by date. They were. She showed him binary search: look at the middle order, decide which half the date is in, and repeat. Finding any order now took about 13 checks instead of up to 5,000.
The idea
-
Linear search: start at the beginning and check each item. Works on any list. For a million items, up to a million checks.
-
Binary search: only for sorted lists. Check the middle. Too high? Throw away the top half. Too low? Throw away the bottom half. For a million items, at most about 20 checks.
Example
This is how you find a word in a paper dictionary: open near the middle, then jump forwards or backwards, never reading page by page.
How it works
Linear search checks items one by one. It works on any list but takes longer as the list grows. Binary search only works on sorted data, but halves the search space with every check.
Each doubling of the data adds just one more step to binary search. That's the idea behind indexes in databases and search engines: keep data organised so lookups don't have to scan everything.
Binary search is famous for off-by-one bugs; a well-known study found many textbook versions had errors. Use the tested version from your language's library where one exists.
In the codebase
For exact lookups by key, a dictionary or a database index is usually even faster than binary search.
Try it
Play the number-guessing game with a friend: they pick a number from 1 to 100, and you guess, hearing only "higher" or "lower". Always guess the middle of the remaining range. You'll never need more than seven guesses, because 2 to the power of 7 is 128, more than 100.
In code, binary search keeps two markers, low and high, and checks the middle. If the target is bigger, low moves just past the middle; if smaller, high moves just before it. When low passes high, the item isn't there.
The catch is the sorting. Sorting takes time too, so binary search pays off when you search the same data many times. For a single search through unsorted data, a simple linear search is fine.
Search engines use a more advanced idea, an inverted index: for every word, a list of the pages containing it. Looking up a word becomes a quick dictionary lookup instead of reading the whole web.
Remember
-
Linear search: simple, works anywhere, slow on big lists.
-
Binary search: needs sorted data, extremely fast.
-
Sorting once can make many later searches cheap.
Algorithms · 6.3
Sorting
Sorting puts items in order. Simple methods compare neighbours and swap; faster ones split the list and merge the pieces.
On the team
Mateo wanted the daily report sorted from biggest order to smallest. He started writing his own sorting loop and got tangled. Valentina pointed him to the built-in sort function, with one line saying how to compare two orders. "Built-in sorts are carefully tested and fast," she said. "Learn how sorting works, then use the library."
The idea
Bubble sort walks through the list comparing neighbours and swapping any pair that's out of order. After each pass, the largest remaining item has "bubbled" to the end.
Bubble sort is easy to understand but slow for big lists. Real languages use faster methods such as merge sort (split in halves, sort each, merge) or hybrids like Timsort, created for Python in 2002. In everyday code you just call the built-in sort:
Watch out
In JavaScript, sort() without a comparison sorts as text, so [10, 9, 100] becomes [10, 100, 9]. Pass (a, b) => a - b for numbers.
How it works
Sorting algorithms differ in how many comparisons and moves they need. Simple methods like bubble sort compare neighbours over and over: easy to understand, but slow on large data. Faster methods like merge sort and quicksort split the data, sort the parts and combine them.
A stable sort keeps items with equal values in their original order, which matters when sorting by one thing after another, such as by date then by amount.
Most modern languages use hybrid algorithms that combine methods. JavaScript and Python's built-in sorts are stable.
Try it
Take ten playing cards, shuffle them and sort them using insertion sort: pick up one card at a time and slide it into the right place among the cards already in your hand. Most people sort cards this way without knowing its name. Then try bubble sort with the same cards, and count how many more swaps it needs.
In JavaScript, sorting numbers has a trap: [10, 2, 33].sort() gives [10, 2, 33] sorted as text, so 10 comes before 2. You need sort((a, b) => a - b) to sort them as numbers. Python's sorted() handles numbers correctly by default.
For most real work, sorting large data is quick: the best general methods sort a million items in well under a second on a modern laptop.
Remember
-
Simple sorts swap neighbours; fast sorts divide and merge.
-
Use the built-in sort in real code.
-
Know whether you're sorting numbers or text.
Algorithms · 6.4
How fast? Big O
Big O describes how the work grows as the input grows. It ignores small details and asks: double the data, what happens to the time?
On the team
Mateo's report worked instantly with 100 orders and took a minute with 10,000. Valentina looked at the code: for each order, it searched the whole list again for that customer's other orders. Doubling the data quadrupled the time. She replaced the inner search with a dictionary built once. With 10,000 orders, it took under a second.
The idea
| Big O | Name | Example | 1,000 items → about |
|---|---|---|---|
| O(1) | Constant | Look up a key in a dictionary | 1 step |
| O(log n) | Logarithmic | Binary search | 10 steps |
| O(n) | Linear | Check every item once | 1,000 steps |
| O(n log n) | "n log n" | Good sorting | 10,000 steps |
| O(n²) | Quadratic | Compare every item with every other | 1,000,000 steps |
Watch out
For small inputs, any method is fine. Big O matters when data grows: code that's fine with 100 users can grind to a halt with 100,000.
How it works
Big-O notation describes how an algorithm's work grows as the input grows, ignoring small details. It answers: if the data doubles, what happens to the time?
- O(log n)
- O(n)
- O(n²)
O(n²) usually comes from a loop inside a loop over the same data, as in Mateo's report. For small inputs, it doesn't matter; for large ones, it can make programs unusable.
Big-O ignores constant factors, so for small inputs a "slower" algorithm can actually be faster. It's a guide for how code scales, not an exact stopwatch.
In the codebase
When code is slow, measure first with a profiler, then look for loops inside loops and repeated work.
Try it
For each of these, guess the growth: finding the largest number in a list, looking up a word in a dictionary data structure, comparing every student with every other student, and binary search in a sorted list. Answers: O(n), about O(1), O(n²) and O(log n).
The most common classes, from fastest to slowest, are O(1), constant time, the same however big the data; O(log n), like binary search; O(n), going through everything once; O(n log n), good sorting algorithms; O(n²), a loop inside a loop; and O(2ⁿ), trying every combination, which becomes impossible quickly.
The practical lesson: with a thousand items, almost any approach is fine. With a million, the difference between O(n) and O(n²) is the difference between a blink and many hours. Big-O helps you spot the problem before your users do, often just by noticing a loop inside a loop.
Space has a Big-O too: an algorithm that copies all the data uses O(n) extra memory.
Remember
-
Big O = how work grows with input size.
-
O(n²) code is a common hidden reason software gets slow.
-
Pick a better algorithm before buying a faster computer.
Algorithms · 6.5
Check: Algorithms
Five questions on searching, sorting and speed.
Craft · 7.1
Reading error messages
An error message is the computer telling you exactly what confused it and where. Reading it carefully solves most problems.
On the team
When Mateo's first error message appeared, he panicked and closed it. Valentina made him open it again and read it slowly, bottom line first: TypeError: Cannot read properties of undefined (reading 'name'), at receipt.js line 42. "It's telling you exactly what and where," she said. On line 42, he'd tried to read the customer's name when no customer had been found.
The idea
Run this. It has a mistake on purpose.
The message says it cannot read properties of undefined: user.address doesn't exist, so asking for its city fails. Errors usually tell you:
-
What kind of problem (a type error, a syntax error, a missing name).
-
Where: the file and line number.
-
What it was trying to do at the time.
Watch out
The line the error points to is where the program noticed the problem. The actual cause is sometimes earlier.
How it works
An error message usually has three parts: the type of error, a description, and a stack trace showing where it happened and which function calls led there.
The stack trace reads like a trail of breadcrumbs: the top line in JavaScript, or the bottom in Python, is usually where it broke; lines below or above show how the program got there. Look for the first line in your own code.
Searching the exact error message online, minus your own variable names, often finds an explanation within minutes.
In the codebase
Good programs also produce good error messages for users: what went wrong, and what they can do about it.
Try it
In the console, type each of these and read the error: consle.log(1), null.length, JSON.parse("{bad}") and let a = ;. For each, find the error type, the message and the line number. Then fix them one by one.
Sometimes the line in the error isn't where the real mistake is. A missing closing bracket on line 10 might only be reported at the end of the file, because that's where the computer finally noticed something was wrong. If a line looks fine, check the lines just before it.
Warnings are different from errors: the program still runs, but something looks suspicious. Don't ignore them; they're often tomorrow's bugs.
When asking for help online or from a colleague, include the full error message, the code that caused it, what you expected, and what you've already tried. A good question often gets answered within minutes, and writing it clearly sometimes reveals the answer before you post.
Remember
-
Read the whole message, slowly.
-
Note the error type and the line.
-
Search the exact message online: someone has almost certainly met it before.
Craft · 7.2
Debugging
Debugging is detective work: form a guess about what's wrong, test it, and narrow down until only the cause is left.
On the team
Some receipts showed the wrong total, but only sometimes. Mateo stared at the code for an hour. Valentina asked him to find one order that went wrong and reproduce it. It only failed when an order had a discount and a delivery fee. Adding a few console.log lines showed the discount was being applied after the fee instead of before. A bug that felt random had a simple cause.
The idea
- Reproduce the bug reliably
- Guess where it might be
- Check with a print or a debugger
- Narrow down
- Fix
- Check the fix and nothing else broke
The simplest tool is printing values as the program runs:
The printout shows item = undefined on the last round: the loop runs once too often. Change <= to < and run again.
Example
Rubber duck debugging: explain your code, line by line, out loud to someone, even a rubber duck. Saying it slowly often reveals the mistake.
How it works
Debugging is detective work: form a hypothesis, test it, narrow down. Random changes waste time and often add new bugs.
- 1Reproducefind exact steps that make it fail every time
- 2Isolateshrink the problem: which input, which function, which line?
- 3Inspectprint values or use a debugger to watch the code run
- 4Fixchange one thing, for a reason you can explain
- 5Testconfirm the fix, and add a test so it never returns
A debugger lets you pause a program at a line, called a breakpoint, and inspect every variable. Browsers include one in their developer tools; most code editors have one too.
Explaining the problem aloud, line by line, often reveals the bug. Programmers call it rubber-duck debugging, after a story of a developer who explained code to a rubber duck.
Try it
This function should return the average of a list but gives the wrong answer: function avg(xs) { let t = 0; for (let i = 1; i < xs.length; i++) t += xs[i]; return t / xs.length; }. Add a console.log inside the loop to watch i and t, and find the bug.
When a bug appeared after a change but you don't know which one, Git can help: git bisect checks out versions halfway between a good and a bad commit, you test each, and it narrows down the exact commit that introduced the bug in a few steps, binary search applied to history.
After fixing a bug, ask why it happened and where else the same mistake might lurk.
Remember
-
Make the bug happen on demand first.
-
Print or inspect values to check your guesses.
-
Change one thing at a time.
Craft · 7.3
Testing
A test is a small piece of code that checks other code gives the right answer. Run tests every time you change something.
On the team
After the receipt bug, Valentina asked Mateo to write tests: tiny programs that check the total for an order with a discount, with a delivery fee, with both, and with none. Two weeks later, he changed the discount rules. One test failed immediately, before any customer saw a wrong receipt. "Tests are a safety net," she said. "They let you change code without fear."
The idea
Good tests cover the normal case and the edges: zero, empty lists, very large numbers, odd inputs like 1900.
How it works
An automated test runs a piece of code with known inputs and checks the output matches what you expect. A test suite runs hundreds or thousands of these in seconds, every time the code changes.
- Unit testsone function at a timefast, many of them
- Integration testsparts working together, such as code plus database
- End-to-end teststhe whole app, as a user would use itslow, fewer
Good tests cover typical cases, edge cases like zero, empty or very large inputs, and error cases. Each bug you fix deserves a test so it can't silently return, known as a regression test.
Continuous integration (CI) runs the tests automatically whenever code is pushed, and blocks changes that break them.
In the codebase
Code that's hard to test is often hard to understand. Small functions with clear inputs and outputs are easy to test.
Try it
Write a function isEven(n) and three tests for it: one even number, one odd number, and zero. In plain JavaScript, console.assert(isEven(4) === true) prints an error only if the check fails. Then deliberately break the function and watch the tests catch it.
Popular test tools include Jest and Vitest for JavaScript and pytest for Python. A typical test has three parts, often called arrange, act and assert: set up the input, run the code, and check the result.
Some teams write tests before the code, called test-driven development: write a failing test describing what you want, write just enough code to pass it, then tidy up. It forces you to decide exactly what "working" means before you start.
Code coverage tools show which lines your tests actually ran. High coverage doesn't prove the code is correct, but untested lines are where surprises live.
Remember
-
Tests catch mistakes before users do.
-
Test edge cases, not just the obvious ones.
-
Real projects use testing tools (Jest, pytest and others) to run thousands of tests in seconds.
Craft · 7.4
Version control and Git
Version control records every change to your code, so you can go back in time, see who changed what, and work with others without overwriting each other.
On the team
Mateo changed the order form, broke it, and couldn't remember what the working version looked like. He had copies named order-final.js, order-final2.js and order-final-REAL.js. Valentina introduced Git. Each saved change became a commit with a message. When he broke something again, he could see exactly what changed and go back in seconds.
The idea
Git, created by Linus Torvalds in 2005 for the Linux project, is by far the most used version-control tool. Sites like GitHub, GitLab and Bitbucket host Git projects online.
-
A commit is a saved snapshot with a message describing the change.
-
A branch is a separate line of work, so you can try something without disturbing the main version.
-
A merge brings a branch's changes back in.
How it works
Git records snapshots of your project called commits. Each commit stores what changed, who changed it, when and why, in a message. Branches let you work on a new feature without disturbing the working version, then merge it back when it's ready.
- 1Editchange files
- 2Stagegit add the changes you want to save together
- 3Commitgit commit with a clear message
- 4Pushsend commits to a shared copy, such as GitHub or GitLab
- 5Pull requestask teammates to review and merge
Good commit messages say why, not just what: "Apply discount before delivery fee (receipt bug)" is far more useful later than "fix".
GitHub and similar platforms host repositories and add reviews, issue tracking and automated tests. GitHub reported more than 100 million developers on its platform in 2023.
Try it
Install Git, make a folder with one text file, and run git init, git add . and git commit -m "First version". Change the file, run git diff to see exactly what changed, and commit again. Then run git log to see your history.
When two people change the same lines in different branches, Git can't decide which version wins, so it reports a merge conflict and marks both versions in the file. You choose what to keep, remove the markers, and commit. Conflicts feel scary at first but are routine on any team; small, frequent commits make them rare and easy.
A .gitignore file lists things Git should never track: passwords and API keys, large generated files, and installed libraries. Committing a secret by mistake is common, and removing it from history is hard, so set up .gitignore before the first commit.
Pull requests also create a written record of why each change was made, which helps future teammates.
Remember
-
Commit small, commit often, with clear messages.
-
Branch to experiment safely.
-
Version control is a safety net and a shared history.
Craft · 7.5
Check: Writing code that works
Five questions on errors, debugging and testing.
Software · 8.1
What happens when you open a website
Your browser looks up the site's address, asks a server for the page, and builds what you see from the reply, usually in under a second.
On the team
When Mateo first put the order page online, a customer in Medellín said it took ages to load. Valentina opened the browser's network tools and showed him every request the page made: the HTML, three fonts, a huge uncompressed photo of arepas, and a map. The photo alone was 6 MB. Compressing it made the page load in under two seconds.
The idea
-
DNS turns a name like
example.orginto a numeric IP address, like a phone book. -
HTTP (and its secure form, HTTPS) is the language the browser and server use. The browser sends a request (GET this page); the server sends a response with a status code and content.
-
Common status codes:
200OK,301moved,404not found,500server error.
How it works
Visiting a web page sets off a chain of requests.
- 1DNSthe browser looks up the address for the domain name
- 2Connecta secure HTTPS connection is set up with the server
- 3Requestthe browser asks for the page
- 4Responsethe server sends HTML, with a status code like 200 or 404
- 5More requestsfor CSS, JavaScript, images and fonts, then the page is drawn
Status codes tell you what happened: 200 means OK, 301 means moved, 404 means not found, 500 means the server failed.
HTTPS encrypts the connection so others on the network can't read or change it. Browsers now warn users about sites without it.
Speed depends on how much is sent and how far it travels. Content delivery networks keep copies of files in data centres around the world, close to users.
In the codebase
The browser's developer tools show every request, its size and timing. They're the first place to look when a page is slow.
Try it
Open any website, press F12 and choose the Network tab, then reload the page. You'll see every request: its type, size, status code and how long it took. Sort by size and find the heaviest file. On many sites, it's an image that could be much smaller.
The web runs on HTTP, which has evolved over the years. HTTP/2 lets many files travel over one connection at once, and HTTP/3, published as a standard in 2022, runs on a newer transport called QUIC that copes better with patchy mobile networks.
Browsers also cache files: once downloaded, a logo or stylesheet can be reused on the next visit without asking the server again. Servers control this with headers that say how long a file stays fresh, which is why changes to a site sometimes don't show until you refresh hard.
Remember
-
Name → address (DNS) → request → response → page.
-
HTTPS encrypts the conversation so others can't read it.
-
A status code tells you what happened.
Software · 8.2
Front end and back end
The front end is what runs on your device and what you see. The back end runs on servers: it stores data, checks rules and does the heavy work.
On the team
Mateo's order page calculated the total in the customer's browser and sent it to the server. Valentina tried something: she opened the browser tools, changed the total to 1 peso, and submitted. The server accepted it. "Never trust the front end," she said. They moved the price calculation to the server, which looked up prices itself.
The idea
| Front end | Back end | |
|---|---|---|
| Runs on | Your browser or phone | Servers in a data centre |
| Built with | HTML (structure), CSS (look), JavaScript (behaviour); Swift, Kotlin for apps | Python, JavaScript (Node.js), Java, Go, C#, PHP and others |
| Job | Show things, react to taps and typing | Store data, check logins, process payments |
Watch out
Never trust the front end for anything important. Users can change what runs in their own browser, so prices, permissions and checks must be confirmed on the server.
How it works
The front end runs on the user's device: it shows the interface and responds to clicks. The back end runs on servers: it stores data, applies business rules, and talks to other services. They communicate through APIs.
- in the browser or app
- HTML, CSS, JavaScript, Swift, Kotlin
- fast feedback, easy to tamper with
- on servers
- Python, JavaScript, Java, Go, PHP and more
- trusted rules, data, payments, security
Anything running on the user's device can be inspected and changed by the user. That's why prices, permissions, payments and anything that matters must be checked on the back end, even if the front end also checks them for a smoother experience.
Full-stack developers work on both sides. Many teams split the work by specialists.
In the codebase
Validate input twice: in the front end for helpful messages, and in the back end for safety.
Try it
On any website with a form, open the developer tools, find the form in the Elements tab, and look at its rules, such as required or maxlength. Now imagine deleting those rules in the tools and submitting. A well-built back end still rejects bad data, because it never relied on the front end's checks.
The front end has its own challenges: making pages work on every screen size, loading quickly on slow phones, being usable with a keyboard or screen reader, and keeping the interface responsive. Frameworks such as React, Vue and Svelte help organise large interfaces into reusable components.
The back end handles concerns users never see: storing data safely, handling thousands of requests at once, sending emails, processing payments, and keeping logs. Back ends often run in the cloud on rented servers, or as serverless functions that only run, and cost money, when called.
Remember
-
Front end: what you see and touch.
-
Back end: data, rules and secrets.
-
"Full-stack" developers work on both.
Software · 8.3
Databases and SQL
A database stores data safely so many people and programs can use it at once. SQL is the long-standing language for asking it questions.
On the team
Mateo stored orders in a big text file. When two orders arrived at the same moment, one sometimes overwrote the other. Valentina moved everything into a small SQL database. It handled simultaneous orders safely, and a single query answered Doña Rosa's favourite question: which arepa sold best last month?
The idea
Most business data lives in tables, like spreadsheets with strict rules. SQL describes what you want, and the database works out how to get it:
SELECT name, city
FROM customers
WHERE country = 'Brazil'
ORDER BY name;| name | city |
|---|---|
| Ana | Recife |
| Bruno | Curitiba |
SQL grew out of IBM research in the 1970s and is still one of the most used languages: 58.6% of developers in Stack Overflow's 2025 survey reported using it (checked November 2026).
Example
Other kinds of database suit other jobs: document stores (like MongoDB) keep JSON-like records; key-value stores (like Redis) are built for speed.
How it works
A database stores data so it survives restarts, can be searched quickly, and stays consistent when many users change it at once.
Transactions are why banks can move money safely: subtracting from one account and adding to another either both happen or neither does, even if the power fails halfway.
Relational databases, such as PostgreSQL, MySQL and SQLite, follow ideas set out by Edgar Codd in 1970. Other kinds, often called NoSQL, store documents, key–value pairs or graphs, and suit different needs.
In the codebase
Back up databases regularly and test restoring them. A backup you've never restored is a hope, not a plan.
Try it
This query finds the best-selling arepa last month: SELECT item, COUNT(*) AS sold FROM orders WHERE order_date >= '2026-10-01' GROUP BY item ORDER BY sold DESC LIMIT 1;. Read it aloud: from orders, keep last month's, group by item, count each group, sort by count, take the top one. SQL reads almost like a sentence.
You can practise SQL for free with SQLite, a tiny database that stores everything in one file and is built into phones, browsers and countless apps. It's thought to be the most widely deployed database in the world.
Good database design avoids storing the same fact twice. Instead of writing the customer's name on every order, store customers in one table and refer to them by ID. Then a name change happens in one place.
Remember
-
Databases keep data safe, consistent and shared.
-
SQL says what you want; the database finds it.
-
Tables connect to each other through IDs.
Software · 8.4
APIs
An API is a menu of requests one program offers to others. It lets apps use maps, payments, weather or AI without building those themselves.
On the team
Doña Rosa wanted order confirmations sent on WhatsApp. Mateo didn't need to build a messaging system: WhatsApp offers an API for businesses. Valentina showed him how to read the API documentation, get a key, send a test message, and handle errors when the service was busy. The first automatic confirmation reached Rosa's own phone, and she called Mateo to say it was magic.
The idea
A weather app doesn't measure the weather. It sends a request to a weather service's API and gets data back, usually as JSON:
How it works
An API, application programming interface, is a set of rules for one program to ask another for data or actions. On the web, most APIs work over HTTP, sending and receiving JSON.
- 1Read the docswhat endpoints exist, what they need, what they return
- 2Get credentialsan API key or token, kept secret
- 3Send a requestmethod, URL, headers, body
- 4Handle the responsesuccess data, or an error code to deal with
- 5Respect limitsrate limits, retries, costs
APIs let small programs stand on the shoulders of giants: payments, maps, messaging, weather and AI models are all available as APIs.
API keys are like passwords. Store them on the server or in secret settings, never in front-end code or public repositories.
In the codebase
Assume any API can be slow, fail or change. Good code sets timeouts, retries carefully and shows a sensible message when a service is down.
Try it
Many public APIs need no key for simple use. In your browser, visit a public test API such as https://jsonplaceholder.typicode.com/todos/1 and look at the JSON that comes back. Then, in the console, try fetch("https://jsonplaceholder.typicode.com/todos/1").then(r => r.json()).then(console.log) to do the same from code.
REST is the most common style for web APIs: each kind of thing has a URL, such as /orders or /orders/42, and the HTTP method says what to do: GET to read, POST to create, PUT or PATCH to update, DELETE to remove. GraphQL is an alternative where the client asks for exactly the fields it needs in one request.
Webhooks reverse the direction: instead of your code asking a service repeatedly whether anything happened, the service calls your server when an event occurs, such as a payment succeeding.
Most APIs are versioned, such as /v1/orders, so that the provider can improve them without breaking apps that rely on the old behaviour.
Remember
-
API = a defined way for programs to talk.
-
Requests go in, structured data (often JSON) comes out.
-
Most APIs need a key, which must be kept secret on the server.
Software · 8.5
Security basics
Every program that touches the internet will be attacked eventually. A few habits prevent most of the common problems.
On the team
A friend who worked in security tested Mateo's order page as a favour. In ten minutes, she'd found that typing a bit of SQL into the name field could reveal other customers' orders. Valentina showed Mateo the fix: parameterised queries, which keep user input as data, never as code. They also added HTTPS, hashed admin passwords and two-step login for the admin page.
The idea
-
Never trust input. Check and clean anything a user or another system sends. Many attacks, like SQL injection, work by sneaking commands into a form field.
-
Never store passwords as plain text. Store a salted hash made with a slow algorithm built for passwords, such as bcrypt or Argon2.
-
Keep secrets out of code. API keys and passwords go in protected settings, not in files you share or upload.
-
Update dependencies. Most software is built on open-source libraries; known holes get fixed in new versions.
-
Give the least access needed. Each part of a system should only reach what it must.
Watch out
Security is not a feature you add at the end. It's cheaper and safer to build it in from the first line.
How it works
Most attacks exploit a few common mistakes. The OWASP Top Ten, a widely used list from the Open Worldwide Application Security Project, ranks the most serious web application risks.
Passwords should never be stored as plain text. Store them using a slow, salted hashing function, such as bcrypt or Argon2, so even a stolen database doesn't reveal them.
The principle of least privilege helps everywhere: each user, program and key gets only the access it needs.
In the codebase
Keep dependencies updated and turn on automated alerts for known vulnerabilities.
Try it
Check whether your own email address has appeared in known data breaches using the free service Have I Been Pwned. If it has, change the password on that site and anywhere you reused it, and turn on two-step login wherever you can. Security starts with your own accounts.
Cross-site scripting, often called XSS, is another common attack: if a site shows user input on a page without escaping it, an attacker can inject a script that runs in other visitors' browsers. Modern frameworks escape text by default, but code that inserts raw HTML bypasses that protection.
Security isn't a feature you add at the end; it's a habit: validate input, check permissions on every request, keep secrets out of code, log suspicious activity, and update regularly. When in doubt, use well-tested libraries for login, encryption and payments rather than building your own.
Remember
-
Validate input; use the database's safe query tools.
-
Hash passwords; protect keys.
-
Update, and limit access.
Software · 8.6
Check: How real software is built
Five questions.
Next steps · 9.1
Choosing a first language
There's no single best language. Pick one that fits what you want to build, learn it properly, and the next one comes much faster.
On the team
By summer, Mateo could build small things in JavaScript. A friend urged him to switch to Rust because it was "faster"; another said Python was "the future". Valentina asked what he wanted to build next: an Android app for the delivery driver. That pointed to Kotlin, or a cross-platform tool with JavaScript he already knew. He stayed with JavaScript and learned React Native.
The idea
| If you want to… | Good first choices |
|---|---|
| Build websites | JavaScript (with HTML and CSS), then TypeScript |
| Work with data, science or AI | Python |
| Make Android apps | Kotlin |
| Make iPhone apps | Swift |
| Build games | C# (Unity), C++ (Unreal) |
| Work on large business systems | Java, C#, Go |
| Get close to hardware, or write fast tools | C, Rust |
| Ask questions of business data | SQL (useful alongside any of the above) |
How it works
The right next language depends on the goal, not on fashion. Ecosystem matters as much as the language itself: libraries, tools, documentation, community and jobs.
Switching too often slows learning. Going deep in one language teaches the concepts that transfer: once you understand variables, functions, data structures and debugging in one, the second language takes weeks rather than months.
Check local job listings too: in many cities, demand clusters around a few languages and frameworks.
Try it
Write down one thing you'd like to build in the next six months. Then search for three open-source projects that do something similar, and look at which languages and frameworks they use. That's a strong hint for what to learn next.
Frameworks matter as much as languages for many jobs. A web developer might use JavaScript with React on the front end and Node.js or Python with Django on the back end. Learning the language first makes frameworks much easier, because you can tell which parts are the language and which are the framework's conventions.
It's also worth learning SQL and Git whatever your main language: almost every programming job uses both. Basic command-line skills, such as moving between folders, running scripts and reading logs, round out the toolkit.
Remember
-
Choose by goal, not by hype.
-
Stick with one language until you can build small things alone.
-
The concepts in this course transfer to all of them.
Next steps · 9.2
Coding with AI assistants
AI tools can write, explain and fix code quickly. They're powerful helpers, but you still need to understand and check what they produce.
On the team
Mateo started using an AI coding assistant. It wrote a function to calculate delivery distances in seconds. He almost shipped it, but Valentina asked him to test it with real addresses first. It used the wrong formula and was off by kilometres for distant streets. With the AI's help, he fixed it, wrote tests, and learned the right formula along the way.
The idea
AI coding assistants predict likely code from your description. They're good at boilerplate, explaining unfamiliar code, suggesting fixes and writing first drafts of tests.
They also make confident mistakes: code that looks right but has subtle bugs, uses functions that don't exist, or has security holes. Developers in surveys report widespread use and also low trust in the output, which is the right instinct.
Watch out
-
Don't paste code you can't explain into anything important.
-
Don't share passwords, keys or private data with online tools.
-
If you're learning, write it yourself first, then compare.
How it works
AI coding assistants are trained on large amounts of code and text. They predict likely code from your prompt and context. They're very good at common patterns and boilerplate, and can explain code, suggest fixes and write tests.
They can also be confidently wrong: inventing functions that don't exist, using outdated APIs, or missing edge cases and security issues. They don't know your business rules unless you tell them.
- explaining unfamiliar code
- first drafts and boilerplate
- suggesting tests
- rubber-duck debugging
- shipping code you don't understand
- security-sensitive code without review
- secrets pasted into prompts
The Stack Overflow Developer Survey 2025 found that most developers now use or plan to use AI tools, while many said they don't fully trust the accuracy of the output.
For learners, the trap is skipping the struggle that builds understanding. Try first, then use AI to check, explain and improve.
In the codebase
Review AI-written code exactly as you would a stranger's: read it, test it and understand it before merging.
Try it
Ask an AI assistant to write a function that checks whether a year is a leap year. Before running it, write four tests: 2024 (leap), 2023 (not), 1900 (not, divisible by 100) and 2000 (leap, divisible by 400). Run the tests. If the AI got it right, ask it to explain the rule; if not, ask it to fix the failing case.
When using AI assistants at work, check your company's rules first. Pasting private code, customer data or passwords into an online tool can break contracts and privacy laws. Many companies use business versions of these tools that don't train on their data.
Writing clear prompts is a skill: describe the goal, give the language and version, include the relevant code and error message, and say what you've tried.
Remember
-
Use AI to speed up, not to skip understanding.
-
Always read, run and test what it gives you.
-
Your value is judgement: knowing what's right, not just what runs.
Next steps · 9.3
How to keep learning
Programmers get good by building things slightly beyond their current skill, again and again. Small finished projects beat big unfinished ones.
On the team
A year after starting, Mateo's ordering tool handled every order for Doña Rosa's shop, and two other family businesses wanted copies. He still felt like he knew nothing. Valentina laughed: "After twelve years, I still look things up every day. The difference is I know what to search for." She suggested a routine: build something small every month, read other people's code, and teach what he learned.
The idea
- Week 1–2Repeat this course's examples from memory, then change them
- Week 3–6Build tiny tools: a tip calculator, a quiz, a to-do list
- Month 2–3One real project you care about, shared online with Git
- After thatRead other people's code, contribute to open source, learn a second language
Example
Free, high-quality places to practise and read: the official documentation of your language, MDN Web Docs for the web, freeCodeCamp, CS50 from Harvard (free online), and exercise sites with automatic checks.
How it works
Programming changes fast, but the fundamentals don't. The habits that keep developers growing are simple and steady.
- 1Buildsmall real projects that solve your own problems
- 2Readother people's code, especially good open-source projects
- 3Sharewrite, teach or explain what you learned
- 4Reviewask for feedback on your code and give it to others
- 5Restregular breaks beat marathon sessions
Open-source contributions are a good next step: fixing documentation, small bugs or tests in projects you use. Many projects label beginner-friendly issues.
Free resources are plentiful: official documentation, MDN Web Docs for the web, freeCodeCamp, Harvard's CS50 lectures online, and language communities on forums and chat.
Try it
Pick a small project you could finish in a weekend: a tip calculator, a to-do list, or a script that renames photos by date. Write down the steps first, build it, put it on GitHub, and share it with one person for feedback. Then pick the next one, slightly harder.
Keep a simple learning log: one line each day about what you learned or what confused you. Over months, it shows how far you've come, which helps on the days you feel stuck, and it becomes a record of problems you've solved before.
Feeling like an impostor is common among programmers at every level. Nobody knows everything; the job is mostly learning, searching and problem-solving. What matters is getting a little better each week, asking good questions, and helping others along the way.
Finally, rest matters. Problems that seem impossible late at night often become obvious after sleep or a walk, because the brain keeps working on them in the background.
Remember
-
Build, don't just watch.
-
Finish small things.
-
Read error messages and documentation; they're the real teachers.
Next steps · 9.4
Check: Your path from here
Four quick questions.