Bitpath

JavaScript: Zero to Hero

Learn to program from nothing, in modern JavaScript: values, decisions, loops, functions, arrays and objects, then errors, modules, classes and asynchronous code. Every lesson has you read, predict, fix and build real programs, and you finish with one you wrote from an empty file.

  • Beginner
  • 8 units, 24 lessons, 312 exercises
  • JavaScript
  • No experience needed

Unit 01 · 3 lessons

First steps

Write a program that calculates with numbers and text, and read the first errors it gives you

  1. > start01Values and expressions
  2. 02Variables
  3. BOSSA receipt
Unit prize
  1. 01
    Values and expressions

    Numbers, text, console.log and arithmetic, one statement at a time

  2. 02
    Variables

    Names for values with let and const, three types, and text built from values

  3. BOSS
    A receipt

    A café bill from prices to a formatted total, and the errors met on the way

Read the unit guide

A program is a list of instructions called statements. JavaScript runs them one at a time, from the top of the file to the bottom, and each one ends with a semicolon. console.log(...) is the instruction you will use most: it prints whatever is inside its brackets on a line of its own.

Values come in types. Numbers are written plainly (7, 3.5). Text is called a string and goes in quotes ("hello"). A boolean is true or false. typeof tells you which one you are holding. Arithmetic follows the order from school: ** (power) first, then *, / and % (the remainder), then + and -. Brackets beat everything.

A variable is a name for a value. const makes a name that keeps its value. let makes one you may reassign. Reach for const first. = means "store the value on the right under the name on the left". The right side is worked out first, which is why score = score + 5 makes sense.

+ adds two numbers but joins two strings, and if either side is a string it joins: "5" + 3 is "53". Convert on purpose with Number("5") and String(5). To build text from values, use a template literal: backticks, with ${...} wherever a value should appear.

Decimals are stored approximately, so 0.1 + 0.2 prints 0.30000000000000004. Do the arithmetic with numbers and format only at the end: total.toFixed(2) gives a string with exactly two decimals.

When a program stops with an error, read it. ReferenceError: x is not defined means a name JavaScript has never seen, usually a typo. TypeError means a value is the wrong kind for what you asked, such as reassigning a const. Lines before the error have already run. Lines after it never do.

Unit 02 · 3 lessons

Decisions and loops

Make a program choose between paths and repeat work, and trace by hand what it will do

  1. 01Conditions
  2. 02Loops
  3. BOSSFizzBuzz and friends
Unit prize
  1. 01
    Conditions

    Comparisons, if and else, and/or/not, the ternary, and values that count as true

  2. 02
    Loops

    while, for and for...of, break and continue, and tracing a loop by hand

  3. BOSS
    FizzBuzz and friends

    Loops and conditions together: FizzBuzz, digit sums, a prime test and the off-by-one

Read the unit guide

A comparison asks a question and gives back a boolean: >, <, >=, <=, === (equal) and !== (not equal). Use the three-character forms. The shorter == converts types before comparing, so 5 == "5" is true, and that hides bugs.

if (condition) { ... } runs its block only when the condition is true. else if adds another test and else catches everything left. Only the first branch whose test is true runs, so put the most specific test first. && means both, || means at least one, and ! flips true and false. For a quick choice between two values there is condition ? a : b.

Any value can stand where a condition is expected. false, 0 and the empty string "" count as false and are called falsy. Nearly everything else counts as true, including the strings "0" and "false".

A loop repeats a block. while (condition) keeps going as long as the condition is true, so something inside must change or it never ends. for (start; condition; step) puts the three parts of a counting loop on one line. for (const ch of text) hands you the characters of a string one by one. break leaves a loop at once, and continue skips to the next round.

To know what a loop does, trace it: write down the variables, then go round by round and update them. Most loop bugs are off by one, from < where <= was meant or a start at 1 instead of 0. Check the first and the last round by hand.

Three patterns cover most loops: a running total that starts at 0, a counter that goes up when a test passes, and a flag that starts as true and is set to false when something rules it out. n % d === 0 is how you ask "does d divide n exactly?".

Unit 03 · 3 lessons

Functions

Package a piece of work under a name, pass values in, get a result back, and know which names it can see

  1. 01Defining functions
  2. 02Arrow functions and scope
  3. BOSSA text toolkit
Unit prize
  1. 01
    Defining functions

    function, parameters and arguments, return against console.log, and undefined

  2. 02
    Arrow functions and scope

    The short way to write a function, where a variable lives, defaults, and a first closure

  3. BOSS
    A text toolkit

    Three small functions built and tested: a palindrome check, a vowel counter, a Caesar shift

Read the unit guide

A function is a named set of instructions. function name(...) { ... } defines it, and nothing runs yet. name(...) calls it, and the block runs, every time you call. Write the work once and use it anywhere.

The names in the brackets of the definition are parameters: variables that each call fills in. The values in the brackets of a call are arguments, matched to the parameters by position. return hands a value back to the caller and ends the function on the spot. A function without a return gives back undefined, JavaScript's value for "nothing here". Printing a result and returning it are different things: only a returned value can be stored or used in further work.

A function is a value, so it can be stored in a variable. The arrow form is the short way to write one: const double = (n) => n * 2;. With no curly brackets, the value of the expression is returned for you. With curly brackets you are back to writing return yourself, and forgetting it gives undefined.

A variable made with let or const lives only inside the curly brackets where it was created: a function body, an if, a loop. Code inside can see names from outside. Code outside cannot see names from inside. A parameter can have a default, (qty = 1), used when the caller leaves that argument out.

A function also keeps access to the variables around the place where it was created, even after that place has finished running. That is called a closure, and it is how a function can remember something between calls.

Small functions with clear names are easy to check: call each one with an input whose answer you already know and compare. Strings help here because they have positions: word.length is the number of characters, word[0] the first one, and word.indexOf("c") the position of a character, or -1 when it is not there.

Unit 04 · 3 lessons

Collections

Keep many values under one name with arrays and objects, and turn a list of records into answers

  1. 01Arrays
  2. 02Objects
  3. BOSSA gradebook
Unit prize
  1. 01
    Arrays

    Lists with positions from 0: reading, adding, removing, copying and sharing

  2. 02
    Objects

    Values under named keys: reading, changing, nesting, unpacking and copying

  3. BOSS
    A gradebook

    An array of objects turned into an average, a best student, groups and a sorted report

Read the unit guide

An array is an ordered list of values in square brackets. Items are numbered from 0, so scores[0] is the first and scores[scores.length - 1] the last. for (const x of scores) walks through the items, and a counting loop with scores[i] does the same when you need the position.

Arrays change. push adds at the end, pop takes from the end, and shift takes from the front. includes answers "is it in there?" and indexOf says where. slice(start, end) copies a part and leaves the array alone, while splice(start, count) cuts items out of the array itself. The two names differ by one letter, so read them twice.

A variable does not hold an array. It holds a reference to it. const b = a gives the same array a second name, and a change made through one name shows through the other. The same goes for an array passed to a function. a.slice() makes a real copy. const stops a name from being pointed at something else. It does not freeze what is inside.

An object groups values under names called keys: { name: "Ana", age: 30 }. Read a value with user.name, or with user[key] when the key is held in a variable. Assigning to a key adds or updates it, and delete removes it. Asking for a key that is not there gives undefined, with no error, so a misspelt key fails quietly.

Object.keys(obj) gives the keys as an array and Object.entries(obj) gives pairs of key and value, so objects can be looped over as well. const { name, age } = user pulls keys out into variables, and { ...user, age: 31 } builds a copy with some keys replaced. Objects are shared by reference exactly as arrays are.

Most real data is an array of objects, and four patterns answer most questions about it: a running total (for a sum or an average), the best seen so far (for a largest or smallest), an object of arrays (for grouping), and sorting a list of names before printing. Test each with an empty array too.

Unit 05 · 3 lessons

Text and data

Turn messy text into tidy data, and data into answers

  1. 01Strings
  2. 02Array methods
  3. BOSSA log report
Unit prize
  1. 01
    Strings

    Cut, clean, search and rebuild text

  2. 02
    Array methods

    map, filter, reduce and a sort that works

  3. BOSS
    A log report

    Parse lines of text, then count, group and rank

Read the unit guide

Most real programs do the same job: take data in one shape and hand it back in another. A line of text becomes a record. A list of records becomes a total, a ranking, a report. This unit gives you the tools for both halves.

Strings come with methods: trim cuts spaces off the ends, split cuts a string into an array, join glues an array back into a string, slice takes a piece, includes searches, replace swaps, padStart fills up to a width. None of them changes the string. Each returns a new one, and it is lost unless you keep it.

Arrays have methods that take a function and do the looping for you. map turns every item into something else: same length, new values. filter keeps the items that pass a test. find returns the first item that passes. some and every answer yes or no. reduce folds the whole array into one value, carrying a running result from item to item.

Because map and filter return arrays, you can chain them: filter, then map, then reduce. Read a chain top to bottom, and write down the array after each step when you are unsure.

sort is the odd one out. It changes the array in place, and with no arguments it compares items as text, which puts 10 before 9. Give it a comparator: (a, b) => a - b for smallest first, b - a for largest first.

The classic pitfall: text that looks like a number is still text. "340" + 10 is "34010". Convert with Number() the moment you parse.

Unit 06 · 3 lessons

Errors and modules

Handle what goes wrong, and split a program into files

  1. 01Errors and missing values
  2. 02Modules and data
  3. BOSSAn inventory that saves itself
Unit prize
  1. 01
    Errors and missing values

    Read a crash, catch it, and handle "nothing"

  2. 02
    Modules and data

    Several files, JSON, Map, Set and a first Date

  3. BOSS
    An inventory that saves itself

    Load JSON, check it, update it, save it, survive bad input

Read the unit guide

Programs fail. A key is missing, a file is cut off, a user types "abc" where a number belongs. When JavaScript cannot carry on, it throws an error: the program stops at that line and prints the error's name, its message and a stack trace, the chain of function calls that led there, most recent first. Read it from the top: what went wrong, then where.

try and catch let you stay in charge. Put the risky lines in try. If one throws, the rest of the block is skipped and catch runs with the error object. finally runs either way. With throw new Error("...") you raise errors of your own, which is how a function refuses bad input instead of quietly returning rubbish.

JavaScript has two values for "nothing". undefined is its own default: a missing key, a function with no return. null is put there by a programmer and means "empty on purpose". Asking either one for a property throws. ?. reads a property only if there is something to read from, and ?? supplies a fallback for exactly these two values, which || would also do for 0 and "".

Bigger programs live in several files, called modules. Each file exports what others may use, and other files import it by name. Everything else stays private to its file.

Data leaves a program as text. JSON.stringify writes objects and arrays as a string; JSON.parse reads the string back into fresh objects, and throws when the text is broken. A Set holds each value once, a Map links keys to values, and a Date holds a moment in time, with months counted from 0.

The classic pitfall: trusting data from outside. Parse it inside try, give missing values a default, check types before you use them, and check before you change anything.

Unit 07 · 3 lessons

Classes and this

Keep data and its rules together in classes

  1. 01Classes
  2. 02This and inheritance
  3. BOSSA bank
Unit prize
  1. 01
    Classes

    Blueprints for objects: constructor, methods, this

  2. 02
    This and inheritance

    How this gets lost, and classes built on classes

  3. BOSS
    A bank

    Accounts, transfers and a history that cannot be broken

Read the unit guide

A class is a blueprint for objects. new Dog("Rex") makes a fresh object, an instance, and runs the class's constructor to set it up. Functions written inside the class are methods: every instance can call them, and each instance has its own data.

Inside a class, this is the object being built or used. Data lives on it: this.name, never a bare name. A getter (get area()) is a method read like a property and computed fresh each time. static members belong to the class itself and are called on its name. A field whose name starts with # is private: only code inside the class can touch it, so the class alone decides what may happen to its data.

this is not fixed when a method is written. It is set by each call: whatever stands before the dot. Take a method off its object and call it bare, or hand it to something that will call it later, and this is undefined. Three fixes: wrap the call in an arrow function, glue the object on with bind, or write the method as an arrow function field.

class Dog extends Animal makes every Dog an Animal too. A method that Dog lacks is looked up on Animal, and so on up the prototype chain. A child constructor must call super(...) before it touches this, and super.method() calls the parent's version of a method the child replaced.

Inheritance is for "is a". Much more often one object simply has another: a car has an engine, a bank has accounts. That is composition, and it is the first thing to try.

The classic pitfall: data that anything can change. A plain object cannot say no. A class with private fields and methods that throw can.

Unit 08 · 3 lessons

Hero

Handle time, build functions from functions, and finish a real program

  1. 01Asynchronous code
  2. 02Closures and iterators
  3. BOSSA task manager
Unit prize
  1. 01
    Asynchronous code

    Timers, promises, async and await

  2. 02
    Closures and iterators

    Functions that remember, and values made on demand

  3. BOSS
    A task manager

    One whole program, from an empty file to tested code

Read the unit guide

Some work takes time: a timer, a file, an answer from a server. JavaScript does not stop and wait for it. It notes what to do when the work is done and carries on with the next line. Code that finishes later is called asynchronous, and the first surprise is always the same: the result is not there yet on the next line.

A promise is an object that stands for a result still on its way. Inside an async function, await pauses that function until the promise settles and then hands you the value, while the rest of the program keeps running. A promise that fails throws at the await, so try and catch work as usual. Promise.all waits for several promises that are running at the same time. Forget an await and you are holding the promise, not the value.

A closure is a function together with the variables that were around when it was made. It keeps them alive and private: a counter nobody else can reset, a multiplier that remembers its factor. Functions that build and return other functions are ordinary JavaScript.

Prefer making new values to changing shared ones. Spread, map and filter build a new array or object with the change in it, and the old one stays valid for everyone who still holds it.

A generator function, written function*, hands out values one at a time with yield and pauses in between, so it can describe a list that never ends. for...of works on anything iterable: arrays, strings, Maps, Sets and generators, but not plain objects.

The capstone puts the whole course into one program: a data model, commands, saving and loading, tests, and a refactor. Small functions, checked data, tests that tell you when you broke something. That is the job.

Learn JavaScript: Zero to Hero on your phone.

Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.

One email when Bitpath is ready to try. Nothing else. Privacy