Reference
Not just "how to write it" but why it exists, where real programs use it, and why JavaScript behaves exactly this way.
94 topics
Basics
- Arithmetic operatorsAddition, subtraction, multiplication, division and the shortcuts
++and+=.Full write-up - Remainder
%The remainder left after dividing one number by another.Full write-up - Variables
letandconstTwo ways to declare a variable:constwon't be reassigned,letwill.Full write-up Number.isInteger()Checks that a value is a whole number — and actually a number.Full write-up- The
MathobjectReady-made maths functions: larger and smaller, absolute value, sign, random numbers, rounding.Full write-up - Rounding:
Math.round,floor,ceil,toFixedThree ways to round to a whole number and one to round to a number of places for display.Full write-up - String → number:
Number(),parseInt(),parseFloat()Numberis a strict conversion;parseInt"pulls a number off the front of a string".Full write-up - Algorithm speed: Big ONot "how many seconds" but "how many times slower when there's more data".Full write-up
- Types of values and
typeofEvery value is a number, a string, a boolean, a "nothing" or an object — andtypeoftells you which.Full write-up nullandundefinedundefinedis "not put in yet";nullis "left empty on purpose".Full write-up- Floating-point precision:
0.1 + 0.2Fractions are stored approximately in binary, so you can't compare them with===, and money is best kept in integers.Full write-up
Conditions
- Comparison:
===,!==,<,>Operators that compare two values and answertrueorfalse.Full write-up if...elseRuns different code depending on a condition.Full write-up- Logical operators
!,&&,||"Not", "and", "or": flip a condition and combine several conditions into one.Full write-up - The ternary operator
? :Picking one of two values on one line.Full write-up
Loops
forloopA loop with a counter: repeats code while a condition holds.Full write-upfor...ofloopA loop that hands you each value of an array, string orSetin turn.Full write-upcontinuein a loopSkips the rest of the current loop step and moves on to the next one.Full write-up- The
whileloopRepeat while a condition holds.Full write-up
Functions
- Function declaration
functionA named piece of code you can run again and again with different data.Full write-up returnEnds the function and hands a value back to whoever called it.Full write-up- Arrow functionsA short way to write a function with
=>, used mostly for callbacks.Full write-up - ClosureA function plus the variables around the place it was created.Full write-up
- ScopeA variable is visible in its block and every nested one — but not outside.Full write-up
- Functions as valuesA function is a value just like a number or a string: it can be stored, passed and returned.Full write-up
- Rest parameters
...argsA function that takes any number of arguments: the extras are gathered into an array.Full write-up - Default parametersA fallback value for an argument that wasn't passed.Full write-up
- RecursionA function that solves a problem by calling itself for the same problem, only smaller.Full write-up
Strings
- Joining stringsJoining strings with
+and appending with+=.Full write-up toUpperCase()andtoLowerCase()Make every letter of a string a capital or lowercase.Full write-upslice()Cuts a piece out of a string or array by index, without changing the original.Full write-uptrim()Removes spaces from the edges of a string.Full write-upsplit()andjoin()Turn a string into an array of pieces and back.Full write-upreplace()andreplaceAll()Swap a piece of a string for another — the first one or all of them.Full write-up- Template literals
`…${}…`A string with "slots" where values are filled in.Full write-up - Regular expressions
/…/A mini-language of patterns: search text not for an exact string but for "something that looks like a phone number".Full write-up
Arrays
- Indexes and
lengthAn item's position in an array or a character's in a string (from zero), and how many there are.Full write-up array.push()Adds items to the end of an array.Full write-uparray.filter()Builds a new array from only the items that pass a check.Full write-uparray.map()Builds a new array by turning every item of the original into something else.Full write-uparray.reduce()Walks an array with an accumulator and returns a single final result.Full write-upincludes()Checks whether a value is in an array, or a piece of text is in a string.Full write-uparray.find()Finds the first item that matches a condition.Full write-upsome()andevery()Answer the questions "is there at least one?" and "are they all?".Full write-up- Spread
..."Spreads out" an array or object to copy it or join it with others.Full write-up sort()andtoSorted()Sorting with a compare function; without one, items are compared as strings.Full write-up- Changing arrays and copiesKnow which methods change an array in place — and make a copy when the original is still needed.Full write-up
flat()andflatMap()"Flattens" nested arrays into one.Full write-up- Stack:
push()andpop()Last put in, first taken out.Full write-up
Objects & collections
SetA collection where every value is stored only once.Full write-up- Property access with
[]Reading and writing an object's property when its name is in a variable:obj[key].Full write-up - Objects
{ }A set of named values: one variable, many related fields.Full write-up Object.keys(),values(),entries()A bridge between objects and arrays: everything arrays can do becomes available to an object.Full write-up- Optional chaining
?.Safe reading of nested properties that may be missing.Full write-up - The
??operatorA default that doesn't mistake "zero" or "empty" for "no value".Full write-up - DestructuringA short way to unpack an object or array into variables.Full write-up
MapA dictionary with any keys, handy methods and a size.Full write-up
Classes and this
- Classes:
classandnewA template for many similar objects: data in fields, behavior in shared methods.Full write-up thisA reference to the object a function was called "on behalf of": the one before the dot.Full write-up- Prototypes and
instanceofAn object that another object "borrows" the properties and methods it doesn't have itself from.Full write-up
Errors
try...catchCatches an error so the program handles it gracefully instead of crashing.Full write-upJSON.parse()andJSON.stringify()Turning data into text and back — for the network, files andlocalStorage.Full write-upthrowandErrorSignal that carrying on is impossible — in a way that can't be ignored.Full write-up
Async
async/awaitA way to write asynchronous code (requests, timers) as if it ran step by step, top to bottom.Full write-up- Promises:
PromiseA value that will be ready later — or an error.Full write-up Promise.all,race,allSettled,anyWaiting for several async operations at once — by different rules.Full write-upsetTimeout()andclearTimeout()Run code later — once.Full write-up
The browser
- The DOM: the page's treeThe page, turned by the browser into a tree of objects that JavaScript can read and change.Full write-up
querySelectorandquerySelectorAllFind elements on the page with the same selector language you use in CSS.Full write-uptextContentandinnerHTMLThe safe way to read or change an element's text — unlikeinnerHTML, which turns the string into markup.Full write-upcreateElement,appendandremoveCreate a new element, put it on the page and take it away — piece by piece, with no HTML strings.Full write-upclassListanddatasetSwitch an element's classes on and off, and keep your own data on it withdata-*.Full write-upaddEventListener: subscribing to an event"When this happens here, call that function."Full write-up- The event object:
event.target,currentTarget,keyA note from the browser: what happened, where, and the details.Full write-up - Event delegation and
closestOne listener on the parent instead of a hundred on the children, thanks to bubbling.Full write-up event.preventDefault(): cancelling the browser's action"Thanks, browser, I'll handle this one."Full write-up- Forms and the
submiteventSubmitting a form is asubmitevent on the<form>;preventDefault()cancels the page reload.Full write-up FormDataAn object with all of a form's fields: name–value pairs, just as they'd be sent.Full write-upvalueandcheckedon form fieldsReading and writing a field's value:valueis a string,checkedis for checkboxes.Full write-upfetch()and theResponseThe browser's built-in function for talking to a server: it sends a request and returns a promise of the response.Full write-up- HTTP: methods, status codes, headersThe language a browser uses to ask a server and get an answer: a method + URL in the request, a status code in the response.Full write-up
localStorageA site's small memory in the browser: strings by key that don't vanish on reload.Full write-up- State → renderData lives in variables, the screen is always redrawn from it; changes go through the data only.Full write-up
Developer tools
- Modules:
importandexportA way to split a program into files: each file hides its own stuff and explicitly gives out what's needed.Full write-up export defaultA file's one "main" export, imported without braces and under any name.Full write-up- npm and
package.jsonA program that downloads other people's code (packages) into your project and keeps track of which versions are where.Full write-up - semver versions:
^and~An agreement on what each of the three version numbers means — so updates can be installed without fear.Full write-up - Stack trace (
error.stack)A printout of who called whom when the error happened: read it top to bottom, from the crash site back to the start of the program.Full write-up consolemethods for debuggingA set of flashlights for testing hypotheses: print a value with a label, a table, a group, an error, a counter or a timing.Full write-updebuggerand breakpointsA freeze-frame of the program: stop at the right line and look at every variable without adding a singleconsole.log.Full write-up- Automated tests:
testandexpectCode that checks code: it calls a function with known data and compares the answer with the expected one.Full write-up - Edge casesInputs at the edges of what's allowed: where code goes wrong most often.Full write-up
- Git: commits, branches, historyA time machine for code: a project history made of snapshots, branches for experiments, and a way to share work with a team.Full write-up
- Merge conflictA place where two branches changed the same thing differently, and git asks a human to decide what to keep.Full write-up