unfried.
Streak:0 days XP:0

Formula sheet

Web development

101 entries in 12 units. Free to use and share.

Jump to a unit (12 units)

Unit 1 Elements and documents

Element, tag and attribute

Also called anatomy of an element, opening tag, closing tag.

<a …> is the opening tag, </a> the closing tag, and the whole line is one a element. href is an attribute name and menu.html its value; Menu is the content the page shows.

<a href="menu.html">Menu</a>

Careful: Attributes go in the opening tag only. Unknown element or attribute names do nothing, and the browser shows no error.

Taught in Attributes and links

Nesting rule

Also called element tree, parent element, overlapping tags.

An element that opens inside another closes inside it, so closing tags come innermost first. The containing element is the parent.

<p>A <b>fresh</b> egg</p>

Careful: Overlapping tags (<b><i>Hi</b></i>) show no error: the browser repairs them, often not as you meant. Indentation never changes the tree.

Taught in Elements inside elements

Image element

Also called img, void element, alt text.

src names the picture's file, fetched separately; alt holds the words that stand in for it. img and br are void elements: no content and no closing tag.

<img src="egg.png" alt="A brown egg">

Careful: Never write </img>, and never leave out alt: without it a screen reader may announce the file name.

Taught in Images and empty elements

Relative paths

Also called file paths, dot dot, absolute URL.

PathStarts fromReaches
egg.pngthe page's folderthe file beside the page
images/egg.pngthe page's folderinto images, then the file
../images/egg.pngthe page's folderup one, into images
/images/egg.pngthe site's top folderimages, from the top
https://example.com/egg.pngnowhere: full addressthe same file from anywhere

Careful: A relative path is read from the folder of the file it is written in, not from the site's top folder or from where the picture is.

Taught in Paths: where files are

Ordered and unordered lists

Also called ul, ol, li, nested list.

ol numbers its items (steps); ul bullets them (items in no order). Every li sits directly inside a ul or ol; a nested list goes inside an li.

<ol>
  <li>Crack the eggs.</li>
  <li>Whisk them.</li>
</ol>

Careful: Do not type numbers into the items: an ol draws its own, so they print twice.

Taught in Lists

Document skeleton

Also called doctype, head, body, html boilerplate.

The head holds facts about the page (the title on the tab, meta lines, style-sheet links); the body holds everything that shows.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Egg Shop</title>
</head>
<body>
  <h1>Egg Shop</h1>
</body>
</html>

Careful: Without the doctype the browser lays the page out in quirks mode, by older rules.

Taught in The document skeleton

Whitespace and character references

Also called collapsing spaces, line break, br, HTML entities, ampersand.

You typeThe page shows
several spaces or line breaksone space
<br>a line break
&lt;<
&gt;>
&amp;&

Careful: Pressing Enter in the file does not start a new line on the page. Use <br>, a new p, or pre to keep the layout as typed.

Taught in What the browser forgives

Unit 2 Meaningful, accessible HTML

Heading outline

Also called heading levels, h1 h2 h3, skipped heading level.

One h1 names the page, each h2 starts a main section, and each h3 is a part of the h2 above it.

<h1>Egg Shop</h1>
<h2>Our eggs</h2>
<h3>Blue eggs</h3>
<h2>Visit us</h2>

Careful: Never choose a level for its size: an h4 straight after an h1 announces two missing levels. Set the size with CSS.

Taught in Headings are an outline

Landmark elements

Also called header nav main footer, page regions, article section.

ElementAnnounced asHolds
headerbannerthe site's name and logo
navnavigationthe menu of links
mainmainthe page's own content, once per page
footercontent informationthe small print

Careful: A div is never a landmark. Use it only for a box that exists for styling. Readers word the announcements differently.

Taught in Landmarks

Also called a versus button, keyboard focus, Tab order.

ControlUse it toKeys
<a href="…">go to a page or fileEnter
<button>do an action on this pageEnter or Space

Careful: A div or span styled as a button takes no focus, so Tab skips it. A link with href="#" is announced as a link and goes nowhere.

Taught in Buttons, links and the keyboard

Alt text

Also called alternative text, decorative image, empty alt.

Imagealt
a chart in a reportthe finding it shows
the only content of a linkwhere the link goes
the only content of a buttonwhat the button does
decoration, or repeats nearby wordsalt=""

Careful: Never start with image of, and never leave alt out: with no alt, readers often announce the file name.

Taught in Alt text

Also called accessible name, click here, read more.

A control's accessible name is the words a screen reader announces: a link's text, an image link's alt, a button's text. Read alone in a list of links, it must say where the link goes, for example Spring menu (PDF).

Careful: Click here, here, read more and learn more make no sense in a list of links, even when the sentence around them explains.

Taught in Link text that makes sense alone

Data table

Also called table header, th scope, caption, tr td.

th cells label a column (scope="col") or a row (scope="row"), and readers repeat them beside each td. caption names the table.

<table>
  <caption>US egg sizes</caption>
  <tr>
    <th scope="col">Size</th>
    <th scope="col">Per dozen</th>
  </tr>
  <tr>
    <td>Large</td>
    <td>24 oz</td>
  </tr>
</table>

Careful: Tables are for data with rows, columns and headers, never for placing parts of a page side by side.

Taught in Tables for data

Labeled form control

Also called label for id, form label, placeholder.

for must match the control's id exactly; a label that wraps its control is connected too. A connected label is announced with the box, and tapping it focuses the box.

<label for="email">Email</label>
<input id="email" type="email">

Careful: A placeholder is not a label: it vanishes while typing and screen readers do not all announce it. A label beside a box with no for is not connected.

Taught in Forms need labels

Input types and built-in validation

Also called required, min max, type email, form validation.

MarkupThe browser refuses
requiredan empty box
type="email"an entry not shaped like an address
type="number" min="1" max="4"numbers below 1 or above 4

Careful: Validation helps people fix entries; it is not security. A server must check every request, since anyone can send one without the page.

Taught in Input types and built-in checks

Unit 3 Selectors and the cascade

Anatomy of a CSS rule

Also called selector, declaration, property and value.

p is the selector; each line inside the braces is a declaration, a property and its value ending in a semicolon. The rule styles every p on the page.

p {
  color: #2e7d32;
  font-size: 20px;
}

Careful: A rule is never used up on its first match. A missing brace or semicolon drops the declarations it touches, and no error shows.

Taught in A CSS rule

Linking a style sheet

Also called link element, external CSS, rel stylesheet.

Goes in the head. rel says the file is a style sheet and href names it, read from the page's folder.

<link rel="stylesheet" href="style.css">

Careful: A style element or attribute styles only its own page or element. Use a linked file to style a whole site from one place.

Taught in A CSS rule

Class and id selectors

Also called dot selector, hash selector, several classes.

A class is for a kind of element that appears many times; an id names one element, once per page.

SelectorSelectsHTML
pevery p element<p>
.saleevery element with class saleclass="sale new"
#cartthe one element with id cartid="cart"

Careful: No dot or # in the HTML attribute. A bare word selects element names, so sale { … } matches nothing.

Taught in Classes and ids

Combinators and selector lists

Also called descendant selector, child selector, compound selector, grouping.

The last part of a selector is the element that gets styled; the parts before it say where it must be.

SelectorSelects
nav aan a anywhere inside a nav
nav > aan a whose parent is a nav
p.notea p that has the class note
h2, h3every h2 and every h3

Careful: .a .b (with a space) is a .b inside an .a; .a.b (no space) is one element with both classes.

Taught in Combining selectors

Pseudo-classes

Also called hover, focus-visible, nth-child, first-child.

Pseudo-classMatches
:hoverwhile the pointer is over it
:focus-visiblefocused, with a visible marker (keyboard)
:first-child, :last-childfirst or last among its siblings
:nth-child(2), (even), (odd)by place among siblings, from 1

Careful: Never remove the focus ring with outline: none. Restyle it on :focus-visible instead.

Taught in States: hover, focus and position

Source order

Also called later rule wins, cascade order.

When two declarations set the same property on one element and their selectors are equally specific, the later one wins. A style sheet linked later in the head counts as later.

Careful: Only the contested property is overridden; the earlier rule's other declarations still apply. Order never beats a more specific selector.

Taught in The cascade: when rules disagree

Specificity

Also called selector weight, id beats class, important.

Compare the counts from the left: ids, then classes and pseudo-classes, then element names. The heavier selector wins wherever it stands in the file.

SelectorIdsClassesElements
p001
p.note011
nav a:hover012
#menu p101

Careful: Counts are never added up: one id beats any number of classes. A style attribute beats every selector and !important beats both, so avoid them.

Taught in Specificity

Inherited and not inherited properties

Also called inheritance, initial value, inherit keyword.

Inherited properties pass from parent to child; the others start at their initial value. color: inherit; takes the parent's value.

InheritedNot inherited
colormargin
font-family, font-sizepadding
line-heightborder
font-stylebackground-color

Careful: A rule on the element itself beats an inherited value, so a link inside brown text keeps the browser's blue until a rule selects the link.

Taught in Inheritance

Why a style did not apply

Also called invalid declaration, CSS typo, computed value.

No error ever shows. Developer tools list the computed value and the rules that matched, with losing declarations crossed out.

CauseExample
invalid declaration, droppedcolour: red;, font-size: 40;
missing semicoloncolor: red then font-size: 20px;
selector matches nothing.prices against class="price"
lost the cascadep against #main p

Careful: A bad declaration drops only itself, and the browser reads on. A missing semicolon drops both declarations it runs together.

Taught in When CSS does nothing

Unit 4 Boxes, color and type

Box model layers

Also called padding, margin, border, content.

From the inside out: content, padding, border, margin. The background fills the content and the padding; the margin is outside the box and transparent.

Careful: Padding and margin are not the same space. To move text away from a box's edge, use padding; to move boxes apart, use margin.

Taught in Every element is a box

Width of a box with the default sizing

Also called content-box, rendered width, total width.

W
width across the borderpx
w
the width value, the contentpx
p
padding on each sidepx
b
border width on each sidepx

Applies: The box has the default box-sizing: content-box and the same padding and border on the left and right.

Careful: With box-sizing: border-box, W=w and the content is w−2p−2b⁠. Margin is never part of the width.

Taught in How wide is the box?

Border-box sizing

Also called box-sizing border-box, universal box-sizing.

width becomes the whole box across its border, and the padding and border fit inside it.

* {
  box-sizing: border-box;
}

Careful: The content gets narrower, not the box wider. Without this rule, width sets the content only.

Taught in How wide is the box?

Margin collapse

Also called collapsing margins, gap between paragraphs.

When a block's bottom margin meets the top margin of the block below, the gap is the larger of the two, not their sum.

Careful: Only vertical margins of blocks in normal flow collapse. Left and right margins add up, and margins inside flex and grid containers never collapse.

Taught in Margins: gaps and centering

Centering a block

Also called margin auto, center a div horizontally.

The two auto margins split the free space, so the block sits in the middle, left to right.

.column {
  max-width: 600px;
  margin: 0 auto;
}

Careful: The block needs a width or max-width narrower than its container. text-align: center centers the text inside, not the box.

Taught in Margins: gaps and centering

Block, inline and inline-block

Also called display, inline box.

div, p, h1 and li are blocks; span, a and em are inline; button and input are inline-block.

displayNew line?Takes width and height?
blockyesyes
inlinenono
inline-blocknoyes
noneno boxno box

Careful: An inline box's top and bottom margins move nothing. To size a link or a span, change its display.

Taught in Block and inline

em and rem

Also called relative units, compounding em, root font size.

s
the length that resultspx
k
the number before em or remno unit
s0
for em, the element's own font size (the parent's, on font-size); for rem, the root font size, 16 by defaultpx

Applies: Any length written in em or rem. For text, use rem: it follows the size a reader sets in the browser.

Careful: Ems compound when elements nest: 20 px, then 1.5em gives 30 px, then 45 px. A rem gives the same size at every level.

Taught in Lengths: px, %, em and rem

Contrast minimums

Also called WCAG contrast, 4.5 to 1, color contrast.

The ratio runs from 1:1 (the same color) to 21:1 (black on white) and is computed from the two colors. #767676 on white is 4.54:1; #777777 is 4.48:1.

TextMinimum ratio
Body text4.5:1
Large text: 24 px, or about 18.7 px bold3:1

Careful: Nothing is rounded: 4.48:1 fails. The ratio depends on the background too, and color alone must never carry meaning.

Taught in Color and contrast

Hex, rgb and hsl

Also called hex color, color notation.

#ffcc00 is red ff (255), green cc (204), blue 00; the same yolk yellow is rgb(255, 204, 0) and hsl(48, 100%, 50%), a hue angle, a saturation and a lightness.

Careful: The pairs go red, green, blue. In hsl() the third number is the lightness: lower it for a darker shade of the same hue.

Taught in Color and contrast

Font stack and line height

Also called font-family fallback, unitless line-height.

The browser uses the first font in the list that the device has; the generic family at the end is always there. A unitless line height is passed down as a factor of each element's own size.

body {
  font-family: Georgia, serif;
  line-height: 1.5;
}

Careful: line-height: 24px passes a fixed 24 px to every element, so a 32 px heading gets cramped lines.

Taught in Readable text

Images that fit

Also called responsive image, max-width 100%.

The image shrinks to the width of its container and keeps its shape, but never stretches past its own size.

img {
  max-width: 100%;
  height: auto;
}

Careful: width: 100% stretches small images too. A fixed width wider than the screen makes the page scroll sideways.

Taught in Keeping content in its box

Percentage padding and margin

Also called padding-top percent, aspect box.

p
the padding or marginpx
k
the percentageno unit
Wc
the width of the containing blockpx

Applies: Any padding or margin written in %, on any side.

Careful: Top and bottom percentages use the container's width too, not its height: padding-top: 10% in a 300 px wide box is 30 px.

Taught in Keeping content in its box

Unit 5 Flexbox

Flex container

Also called display flex, flex items, main axis.

The direct children of .row line up along the main axis, left to right by default, each as wide as its content. flex-direction turns the axis (row, row-reverse, column, column-reverse).

.row {
  display: flex;
}

Careful: Grandchildren are not flex items. display: flex goes on the parent of the items, not on the items.

Taught in A flex container

justify-content values

Also called main axis alignment, space-between, space-around.

justify-content places items along the main axis, which decides where the free space goes.

ValueThe items
flex-startpacked at the start (default)
centerpacked in the middle
flex-endpacked at the end
space-betweenfirst and last at the edges, equal gaps
space-aroundequal space around each, half at the edges

Careful: With one item, space-between leaves it at the start. In a column, justify-content works top to bottom.

Taught in Spreading items out

align-items and the cross axis

Also called cross axis, vertical centering, stretch.

align-items places items along the cross axis: flex-start, center, flex-end, or the default stretch, which makes every item fill the cross axis.

Directionjustify-contentalign-items
rowleft to righttop to bottom
columntop to bottomleft to right

Careful: Justify is not always horizontal: each property follows its axis, and a column swaps both.

Taught in The cross axis

Row width with gaps

Also called gap, flex-wrap, how many fit.

W
row width needed to hold the items on one linepx
n
number of itemsno unit
w
width of one itempx
g
the gappx

Applies: The items keep their widths and sit on one line. With flex-wrap: wrap, an item that would make the line wider than the row starts a new line.

Careful: A gap only goes between items, never at the edges, so n items have n − 1 gaps. Without flex-wrap: wrap the items shrink instead of wrapping.

Taught in Wrapping and gaps

Sharing out leftover space with flex-grow

Also called flex-grow, flex-basis, flex shorthand.

wi
width of item ipx
bi
basis of item i (its width when the basis is auto)px
gi
flex-grow of item ino unit
G
sum of the grow valuesno unit
W
row width, less the gapspx
B
sum of the basespx

Applies: The bases add up to less than the row, so there is leftover space. flex: 1 sets a grow of 1 and a basis of 0, so the whole row is shared.

Careful: With a basis of auto, flex-grow: 2 gets twice the share of the leftover, not twice the width. If the bases overflow the row, items shrink instead.

Taught in Growing and shrinking

Centering both ways

Also called vertical centering, center a div.

Centers the card's child left to right and top to bottom, whatever its size.

.card {
  display: flex;
  justify-content: center;
  align-items: center;
}

Careful: The container must be taller than the item, or there is no room to center it in. Alignment properties go on the container, never on the item.

Taught in Centering, and pushing with auto

Auto margin in a flex row

Also called push to the right, margin-left auto.

An auto margin on a flex item takes all the free space on that side, so the item and those after it move to the far end.

.cart {
  margin-left: auto;
}

Careful: margin-right: auto puts the space after the item instead. An auto margin never changes the order of items.

Taught in Centering, and pushing with auto

Visual order and source order

Also called row-reverse, order property, focus order.

row-reverse, column-reverse and order change only where items are drawn. Keyboard focus and screen readers follow the order of the HTML.

Careful: To show items in another order, move them in the HTML, so screen, keyboard and screen reader agree.

Taught in Order on screen, order in the source

Unit 6 Grid

Grid container

Also called display grid, grid-template-columns, tracks.

The direct children of .box fill three 100 px columns, row by row, left to right. The grid adds a row whenever the last one is full.

.box {
  display: grid;
  grid-template-columns: 100px 100px 100px;
}

Careful: Widths are separated by spaces, not commas: with commas the declaration is dropped and the grid has one column. Grandchildren are not grid items.

Taught in Rows and columns

Width of an fr column

Also called fr unit, fraction, gap, column width.

w
width of the columnpx
f
the column's number of frno unit
F
sum of the fr numbers of all columnsno unit
W
width of the grid's content boxpx
Fpx
sum of the fixed (px) column widthspx
n
number of columnsno unit
g
the column gappx

Applies: The content of each fr column fits in its share, which is the usual case for short text.

Careful: The gaps and the fixed columns come out before the sharing. 1fr 2fr with a 30 px gap in 300 px gives 90 and 180 px, not 100 and 200.

Taught in The fr unit and gaps

repeat()

Also called repeat function.

Short for 1fr 1fr 1fr: the first number is how many times the tracks after the comma repeat. It mixes with other tracks, as in 200px repeat(2, 1fr).

grid-template-columns: repeat(3, 1fr);

Careful: The count comes first. repeat(1fr, 3) is invalid and dropped.

Taught in The fr unit and gaps

Placing by grid lines

Also called grid-column, grid-row, line numbers, span.

Grid lines are the edges between tracks, numbered from 1: n columns have n + 1 lines. An item spanning k tracks is k tracks wide plus the k − 1 gaps between them.

DeclarationIn a 3-column grid
grid-column: 1 / 3the first two columns
grid-column: 2 / 4the last two columns
grid-column: 1 / 4all three columns
grid-column: span 2two columns, from where the item lands
grid-row: span 2two rows tall

Careful: The numbers count lines, not columns, so 1 / 3 covers two columns. Asking for a line beyond the last makes the grid add a track.

Taught in Placing and spanning

Named grid areas

Also called grid-template-areas, grid-area, page layout.

One string per row, one word per cell; cells with the same name make one area. grid-area puts an element in the area with that name.

.page {
  display: grid;
  grid-template-columns: 100px 1fr;
  grid-template-areas:
    "head head"
    "side main"
    "foot foot";
}
nav {
  grid-area: side;
}

Careful: Every area must be a rectangle and every row the same number of cells, or the whole template is dropped. A name in a rule that the template lacks makes the grid add a track for the element.

Taught in Named areas

As many columns as fit

Also called auto-fit, minmax, responsive grid.

As many columns of at least 150 px as fit, each stretched to one share of the row. The largest n with n × 150 + (n − 1) × gap no wider than the row is the column count.

grid-template-columns:
  repeat(auto-fit, minmax(150px, 1fr));

Careful: The smallest size comes first in minmax, and it can't be in fr: minmax(1fr, 150px) is dropped. A fixed count such as repeat(5, minmax(150px, 1fr)) scrolls sideways on a phone.

Taught in As many columns as fit

Grid or flexbox

Also called choosing a layout, one direction or two.

Flexbox for one direction, with items sized from their content; grid for rows and columns that line up.

LayoutUse
nav links, tag cloud, card footerflexbox
gallery, page frame, form columnsgrid

Careful: Neither replaces the other. Any grid item can be a flex container, and many pages use grid for the frame and flexbox inside.

Taught in Grid or flexbox?

Unit 7 Responsive design

The viewport line

Also called meta viewport, device-width, zoomed-out page.

In the head. Lays the page out at the device's width in CSS pixels and starts it unzoomed.

<meta name="viewport"
  content="width=device-width, initial-scale=1">

Careful: Without it, a phone lays the page out at a desktop width and shrinks it, however fluid the CSS. A fixed number such as width=1024 does the same.

Taught in The viewport line

Fluid width with a cap

Also called max-width, centered container, fluid layout.

main fills the room it has up to 960 px and is centered beyond that; images never get wider than their container.

main {
  max-width: 960px;
  margin: 0 auto;
}
img {
  max-width: 100%;
}

Careful: width: 960px and min-width: 960px both stop the box shrinking, so a phone scrolls sideways.

Taught in Fluid layouts

Which widths a media query covers

Also called min-width, max-width, breakpoint.

Both include the width itself. Rules inside a query apply only while it holds.

QueryHolds when the viewport is
(max-width: 600px)600 px wide or narrower
(min-width: 600px)600 px wide or wider

Careful: max-width does not mean "wider than": it is a ceiling. A query tests the viewport, not the element it styles.

Taught in Media queries

Mobile-first order

Also called order of media queries, cascade, desktop first.

Phone styles with no query, then min-width queries from the smallest width up. Where several hold, the later rule wins at equal specificity.

.grid { display: grid; }
@media (min-width: 600px) {
  .grid { grid-template-columns: 1fr 1fr; }
}
@media (min-width: 900px) {
  .grid { grid-template-columns: 1fr 1fr 1fr; }
}

Careful: Out of order, a wide screen gets the narrower layout. A query adds no specificity, so a more specific selector outside it still wins. Desktop first uses max-width queries from the largest width down.

Taught in Mobile first

clamp() for font size

Also called clamp, fluid type, vw.

s
the size usedpx
a
the minimum, the first value (a rem value times 16 px at the default root size)px
p
the preferred size, the middle value (6vw is 6 % of the viewport's width)px
b
the maximum, the last valuepx

Applies: The minimum is smaller than the maximum. clamp(2rem, 6vw, 3rem) gives 32 px at 390 px, 42 px at 700 px and 48 px at 1600 px.

Careful: clamp takes exactly three values; with two, the declaration is dropped. A vw size alone has no limits and ignores the reader's text setting, while rem limits follow it.

Taught in Type that scales

Device pixels an image needs

Also called srcset, w descriptor, device pixel ratio.

D
dots across the image fills on screendots
w
the width the image shows atCSS px
r
screen dots per CSS pixelno unit

Applies: Choosing among srcset files: the smallest file at least D pixels wide looks sharp with the least download. A 390 px phone at 3 dots per CSS pixel needs 1170.

Careful: CSS sizes such as max-width: 100% change the size shown, never the file downloaded. srcset widths are written with w (1200w).

Taught in Images that fit the screen

Ways to hide content

Also called display none, visibility hidden, visually hidden.

Hide on some screens only by putting display: none inside a media query.

WaySpace kept?Screen readers
display: nonenodon't read it
visibility: hiddenyesdon't read it
visually hidden classno (1 px)read it

Careful: Text hidden with display: none gives a control no name. A skip link must not use display: none, or Tab can never reach it.

Taught in Respecting the reader's settings

User preference queries

Also called prefers-color-scheme, dark mode, prefers-reduced-motion.

Holds for readers who set their device to dark mode. #f5f5f5 on #1a1a1a is 15.96:1. prefers-reduced-motion: reduce holds for readers who asked for less motion.

@media (prefers-color-scheme: dark) {
  body {
    background-color: #1a1a1a;
    color: #f5f5f5;
  }
}

Careful: Change the background and the text color together: the default black text on #1a1a1a is 1.21:1, far under 4.5:1. Reduced motion means no movement, not slower movement.

Taught in Respecting the reader's settings

Unit 8 JavaScript values and variables

Operator precedence in JavaScript

RankOperatorsGroups
1 (first)( )inside out
2**right to left
3* / %left to right
4 (last)+ -left to right

Careful: / never rounds: 7 / 2 is 3.5. Use Math.floor(a / b) for whole groups and a % b for what is left.

Taught in Numbers and arithmetic

Division, remainder and Math.floor

Also called modulo, mod, integer division.

Math.floor(a / b) full groups of b fit in a, with a % b left over: 135 seconds is Math.floor(135 / 60) = 2 minutes and 135 % 60 = 15 seconds.

7 / 2               // 3.5
Math.floor(7 / 2)   // 3, rounds down
7 % 2               // 1, the remainder
1 / 0               // Infinity
0 / 0               // NaN

Careful: NaN and Infinity are number values, not errors: the script carries on, and any arithmetic with NaN gives NaN.

Taught in Numbers and arithmetic

Template literals

Also called string interpolation, backticks.

const n = 3;
`n is ${n * 2}`   // "n is 6"
"n is ${n}"       // "n is ${n}"

Careful: Only backticks fill in ${…}. Double and single quotes print it as typed.

Taught in Strings and template literals

let and const

const names can never be assigned again; let names can. Use const unless the value must change.

let count = 0;
count += 5;        // fine: 5
const price = 4;
price = 5;         // TypeError

Taught in let and const

typeof results

Valuetypeof
42, 3.5, NaN"number"
"42", `5`"string"
true, false"boolean"
undefined"undefined"
null, [1, 2]"object"

Careful: typeof can't tell arrays or null from objects. Use Array.isArray(v) for arrays.

Taught in Types and typeof

Type coercion with + and other operators

+ joins when either side is a string; -, * and / turn strings into numbers. Work left to right.

"3" + 4        // "34", joined
"3" * 4        // 12
1 + 2 + "3"    // "33"
"1" + 2 + 3    // "123"

Careful: Put a sum in parentheses before it meets a string: "Score: " + (9 + 1) is "Score: 10".

Taught in When types mix

Converting strings and numbers

Also called Number, parseInt, parseFloat, toFixed.

CallGives
Number("3.5")3.5
Number("12px")NaN
parseInt("12px")12
parseFloat("3.5em")3.5
(21.456).toFixed(1)"21.5", a string

Careful: toFixed gives text, so do the arithmetic first. NaN === NaN is false: test with Number.isNaN(x).

Taught in Converting on purpose

JavaScript error types

ErrorUsual cause
ReferenceErrora misspelled or undeclared name
TypeErrora property of undefined or null; a new value for a const
SyntaxErrora missing comma, quote or bracket; nothing runs

Careful: The line named is where the problem showed; the cause can be on an earlier line.

Taught in Reading an error

Unit 9 Decisions, loops and functions

Strict and loose equality

Also called triple equals, comparison.

Every comparison (===, !==, <, >, <=, >=) gives a boolean, true or false.

5 === 5      // true
5 === "5"    // false: different types
5 == "5"     // true: == converts first
5 !== "5"    // true

Careful: One = assigns, even inside an if: if (x = 5) stores 5 and always runs. Compare with ===.

Taught in Strictly equal

if, else if, else

Only the first block whose condition is true runs; else runs when none is. Put the strictest test first.

if (score >= 90) {
  console.log("A");
} else if (score >= 80) {
  console.log("B");
} else {
  console.log("C or below");
}

Careful: Without braces, only the next statement belongs to the if. Indentation changes nothing.

Taught in if, else if, else

Falsy values

Also called truthy, truthiness.

Falsy (count as false)Truthy examples
falsetrue
0, NaN1, -3
"""0", "false", " "
null, undefined[]

Careful: A non-empty string is truthy whatever it spells, and an empty array is truthy.

Taught in Truthy, falsy, and, or

Default values with || and ??

Also called nullish coalescing, logical or.

a || b gives a if it is truthy, otherwise b. a ?? b gives b only when a is null or undefined.

0 || 10      // 10
0 ?? 10      // 0
null ?? 10   // 10

Careful: Use ?? when 0 or "" is a real value; || would replace it.

Taught in Truthy, falsy, and, or

for loop header

Also called counting loop.

let i = 1 runs once; i <= 4 is tested before every iteration; i++ (i += 1) runs after each. This loop runs for 1, 2, 3 and 4.

for (let i = 1; i <= 4; i++) {
  total += i;
}

Careful: < stops before its limit and <= includes it: i = 0; i < 5 and i = 1; i <= 5 both run five times.

Taught in Loops: while and for

Functions and return

A call runs the body with the arguments in the parameters, and return hands the value back and ends the call.

function area(w, h) {
  return w * h;
}
area(3, 4)   // 12

Careful: A function with no return gives undefined, even when its body prints the value.

Taught in Functions and return

Missing arguments and default parameters

Arguments fill parameters in order. A missing argument is undefined (or the default, if one is written); extra arguments are ignored.

function add(a, b = 10) {
  return a + b;
}
add(1)      // 11
add(1, 2)   // 3

Careful: No error is reported for a missing argument: area(3) quietly gives NaN.

Taught in Parameters, arguments and defaults

Arrow functions

Without braces, the arrow returns its expression. With braces, the body needs return.

const double = n => n * 2;
const add = (a, b) => a + b;
const half = n => {
  return n / 2;
};

Careful: n => { n * 2 } returns undefined: braces and no return.

Taught in Arrow functions

Block scope of let and const

Also called scope, ReferenceError.

A let or const can be used from its line to the } of the nearest braces around it; a for header's let belongs to the loop. A function can read names declared outside it.

Careful: Outside its block, or before its line, the name gives a ReferenceError. Old code's var ignores blocks.

Taught in Where a variable lives

Unit 10 Arrays and objects

Reading arrays

Also called index, length, last item.

const a = [72, 95, 88];
a[0]              // 72
a.length          // 3
a[a.length - 1]   // 88, the last
a.at(-1)          // 88
a[3]              // undefined

Careful: Indexes run from 0 to length - 1. Past the end gives undefined, not an error; the error comes when that value is used.

Taught in Arrays

for...of and for...in

Also called looping over an array.

for (const x of ["a", "b"]) {}  // "a", "b"
for (const i in ["a", "b"]) {}  // "0", "1"

Careful: for...in gives indexes as strings, so i + 1 joins ("01"). Use for...of for the items.

Taught in Looping over arrays

Methods that change the array and methods that copy

Also called mutate, in place.

Changes the arrayReturns something new
push (new length), pop (item)slice, concat (new array)
splice (removed items)map, filter (new array)
sort, reverse (same array)join (string)

Careful: b = a.sort() does not make a copy: b and a are the same, sorted array. Copy first with [...a] or a.slice().

Taught in Change it or copy it

map, filter and forEach

Also called callback.

[1, 2, 3].map(x => x * 2)      // [2, 4, 6]
[4, 9, 1].filter(n => n > 5)   // [9]
[1, 2, 3].forEach(x => x * 2)  // undefined

Careful: Pass the function itself: map(double). map(double()) calls it at once and hands map its result, which is not a function.

Taught in map and filter

Sorting numbers with a comparator

A comparator returns a negative number when its first item should come first.

[10, 9, 1, 100].sort()          // [1, 10, 100, 9]
a.sort((x, y) => x - y)         // smallest first
a.sort((x, y) => y - x)         // largest first

Careful: sort() with no comparator compares items as text, so numbers come out in dictionary order.

Taught in sort and reduce

Totals with reduce

Also called sum, accumulate.

The callback gets the value so far and the next item and returns the new value so far; the last argument is the starting value.

a.reduce((sum, n) => sum + n, 0)
[].reduce((s, n) => s + n, 0)   // 0

Careful: Leave out the starting value and an empty array throws TypeError: Reduce of empty array with no initial value. A product starts at 1, not 0.

Taught in sort and reduce

Object properties, dot and brackets

Also called object, property, key.

const egg = { size: "large" };
const key = "size";
egg.size     // "large"
egg[key]     // "large"
egg.key      // undefined

Careful: A missing property gives undefined; reading a property of undefined throws a TypeError.

Taught in Objects

References and spread copies

Also called aliasing, shallow copy.

const b = a;         // same array
const c = [...a];    // new array
const o2 = { ...o }; // new object
[1, 2] === [1, 2]    // false

Careful: Spread copies one level: an array inside an object is still shared. const stops a = … but not a.push(…).

Taught in Two names, one array

find

people.find(p => p.name === "Bo")  // Bo's record
people.find(p => p.age > 50)       // undefined

Careful: find returns one record or undefined; filter always returns an array.

Taught in Arrays of objects

Unit 11 The DOM and events

Finding elements with querySelector

Also called querySelectorAll, NodeList, select an element.

CallGives
document.querySelector("p")the first p, or null
document.querySelectorAll("p")a NodeList of every p
[...document.querySelectorAll("p")]an array of every p

Careful: A NodeList has forEach and length but no map or filter. A selector that matches nothing gives null, and using it as an element throws a TypeError.

Taught in Finding elements

textContent and innerHTML

Also called change text, set text, cross-site scripting.

h.textContent = "<em>Hi</em>";
// shows <em>Hi</em>
h.innerHTML = "<em>Hi</em>";
// shows Hi in italics

Careful: Never put text a visitor typed into innerHTML; use textContent.

Taught in Changing text and attributes

classList

Also called add a class, toggle a class, change style.

CallDoes
el.classList.add("x")puts x on
el.classList.remove("x")takes x off
el.classList.toggle("x")on if off, off if on
el.classList.contains("x")true or false

Careful: el.className = "x" replaces every class the element had.

Taught in Styles through classes

Where the script tag goes

Also called defer, script in head, script placement.

A plain <script src="app.js"> runs where it stands and sees only what is above it. Put it last in the body, or in the head as <script src="app.js" defer>, which runs after the whole page is read.

Careful: defer has no effect on a script written between the tags, without src.

Taught in When the script runs

addEventListener

Also called event listener, click handler, on click.

btn.addEventListener("click", addEgg);
btn.addEventListener("click", () => addEgg());

Careful: addEventListener("click", addEgg()) calls addEgg once during setup and hands over its return value; taps then do nothing.

Taught in Listening for events

The event object and bubbling

Also called event.target, currentTarget, event delegation, closest.

PropertyIs
event.targetthe element tapped
event.currentTargetthe element whose listener runs
event.target.closest("li")the nearest li at or above it
event.preventDefault()cancels the browser's own action

Careful: A click runs the listeners of the element tapped and of every ancestor, innermost first.

Taught in The event object and bubbling

createElement and append

Also called add an element, build a list from data.

for (const egg of eggs) {
  const li =
    document.createElement("li");
  li.textContent = egg;
  list.append(li);
}

Careful: A new node shows only after it is appended. Make it inside the loop; appending one node again moves it.

Taught in Building elements from data

Handling a form's submit

Also called preventDefault, submit event, input value.

form.addEventListener("submit", (e) => {
  e.preventDefault();
  total += Number(qty.value);
});

Careful: qty.value is always a string, so total + qty.value joins text. Without preventDefault() the page reloads.

Taught in Forms with JavaScript

Unit 12 Data from the network

JSON.parse and JSON.stringify

Also called JSON, parse JSON, serialize.

JSON.parse turns JSON text into values; JSON.stringify turns values into JSON text.

const data = JSON.parse('{"eggs": 12}');
data.eggs                          // 12
JSON.stringify({ a: undefined, b: 2 })
// '{"b":2}'

Careful: A reply from a server is a string until it is parsed: reply.eggs on the text is undefined.

Taught in JSON

JSON rules

Keys and strings in double quotes. Values: numbers, strings, true, false, null, arrays, objects. Commas only between items.

Careful: Single quotes, bare keys, trailing commas and undefined all make JSON.parse throw a SyntaxError.

Taught in JSON

HTTP status code families

Also called status codes, 404, 500.

CodeMeans
2xx (200, 201)success
4xx (401, 404)a fault in the request
5xx (500)the server failed

Careful: Every status is an answer from a server. With no network no response arrives, so there is no status at all.

Taught in Requests and responses

Order of output with timers and promises

Also called event loop, callback queue.

First the running script, to its end. Then promise callbacks (then, code after an await). Then timers, earliest due first.

Careful: A 0 ms timer still waits for the running script and for promise callbacks.

Taught in Promises

async and await

await pauses only the async function it is in and gives the fulfilled value. An async function always returns a promise.

async function count() {
  const eggs = await getEggs();
  console.log(eggs.length);
}

Careful: await outside an async function is a SyntaxError in a script.

Taught in async and await

Fetching JSON safely

Also called fetch, response.ok, try catch.

try {
  const res = await fetch(url);
  if (!res.ok) {
    throw new Error(res.status);
  }
  const data = await res.json();
} catch (err) {
  // no network, a bad status or bad JSON
}

Careful: fetch rejects only when no response arrives. A 404 or 500 fulfills it, so test res.ok.

Taught in fetch, ok and errors

Loading, data and error states

Set the loading message before the fetch; replace it with the data in try, or with an error message in catch. Give the message element aria-live="polite".

Taught in Data on the page