React Course1.0.0 beta 19

Cheat sheets

Cheat sheets

The most important things on one page – useful JavaScript, array methods, React hooks and TypeScript in React, the most used first. Print them or keep them open next to your code.

Values and conversions

I want…Code
a variable that won’t change / will changeconst name = 'Anna' let count = 0
to find out the type of a valuetypeof x // 'string', 'number'…
text to a numberNumber('42') // NaN when it can't
is it a valid number?Number.isNaN(n) // true = not a number
a number to textString(42)
yes/no from anythingBoolean('') // false
compare exactly (always)a === b a !== b

In detail: lesson JavaScript 01.

Text

I want…Code
to put a value into text`Hello, ${name}!`
to trim spacess.trim()
upper / lower cases.toUpperCase() s.toLowerCase()
contains? starts? ends?s.includes('x') s.startsWith('x') s.endsWith('x')
a piece of the texts.slice(0, 5) s.slice(-3)
to replace every occurrences.replaceAll('-', '/')
to split into an array / join an arrays.split(', ') arr.join(', ')
to pad with a zero on the leftString(7).padStart(2, '0') // '07'
to sort alphabetically by languagea.localeCompare(b, 'en')

Numbers

I want…Code
to round / down / upMath.round(x) Math.floor(x) Math.ceil(x)
to two decimal places (a number)Math.round(x * 100) / 100
the largest / smallestMath.max(...nums) Math.min(...nums)
the remainder (even/odd)n % 2 === 0
a random whole number 1–6Math.floor(Math.random() * 6) + 1
a number for people (separators)n.toLocaleString('en-US')
a price in dollarsnew Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }).format(n)

In detail: lesson JavaScript 01 and lesson JavaScript 08.

Objects

I want…Code
to read a property (also by a variable)user.name user[key]
to unpack properties into variablesconst { name, city = '?' } = user
a copy with a change{ ...user, city: 'Boston' }
without one propertyconst { password, ...rest } = user
keys / values / pairsObject.keys(o) Object.values(o) Object.entries(o)
to go through all pairsfor (const [key, value] of Object.entries(o)) { … }
to translate a value with a dictionaryLABELS[status] ?? 'Unknown'

In detail: lesson JavaScript 03.

Conditions in one expression

I want…Code
one of twoisDone ? 'Done' : 'To do'
a default only for null/undefinedcount ?? 0
to read only when the object existsuser?.address?.city
something or nothing (in JSX)items.length > 0 && <List />
to end a function earlyif (!user) return null

In detail: lesson JavaScript 06.

Functions

I want…Code
a short function with a resultconst double = (n) => n * 2
to return an object from an arrow(name) => ({ name })
a default parameter valuefunction greet(name = 'host') { … }
any number of argumentsfunction sum(...nums) { … }
to pass a function for latersetTimeout(() => greet('Anna'), 1000)

In detail: lesson JavaScript 02.

Waiting and the server

I want…Code
to wait for a resultconst user = await fetchUser(1)
to catch an errortry { … } catch (e) { … } finally { … }
several things at onceconst [a, b] = await Promise.all([loadA(), loadB()])
to load JSON from a serverconst data = await (await fetch('/api/x')).json()
to call later / repeatedlysetTimeout(fn, ms) setInterval(fn, ms)

In detail: lesson JavaScript 07.

Built-in helpers

I want…Code
an object to text and backJSON.stringify(o) JSON.parse(text)
to save in the browserlocalStorage.setItem('key', JSON.stringify(o))
today's date for peoplenew Date().toLocaleDateString('en-GB')
the current time in msDate.now()
a deep copystructuredClone(o)
a unique idcrypto.randomUUID()

In detail: lesson JavaScript 08.