Tutorials › JavaScript Tutorial › JavaScript Reference

JavaScript Reference

15 min read · Lesson 22 of 23

This page collects the most common JavaScript keywords, operators and built-in methods in one place. Use it as a quick lookup while you code. Each section links back to the lesson that explains it in detail.

Keywords

KeywordPurposeLesson
letDeclare a variable that can be reassignedVariables
constDeclare a variable that cannot be reassignedVariables
varOld-style function-scoped variable (avoid)Variables
if / elseRun code depending on a conditionConditions
switch / case / defaultChoose between many fixed optionsConditions
for / while / doRepeat codeLoops
break / continueLeave a loop / skip to the next roundLoops
function / returnDefine a function / send back a valueFunctions
class / extends / superDefine classes and inheritanceClasses
newCreate an instance of a classClasses
thisThe object a method was called onObjects
async / awaitWrite promise-based code step by stepAsync JavaScript
try / catch / finally / throwHandle and raise errorsErrors
typeofGet the type of a value as a stringData Types
instanceofCheck if an object was made from a classClasses

Operators

OperatorMeaningExample
+ - * /Add, subtract, multiply, divide10 / 4 → 2.5
%Remainder10 % 4 → 2
**Power3 ** 2 → 9
++ / --Increase / decrease by 1i++
= += -= *= /=Assignmenttotal += 50
=== / !==Strictly equal / not equal5 === "5" → false
> < >= <=Compare7 >= 7 → true
&&Logical ANDtrue && false → false
||Logical ORfalse || true → true
!Logical NOT!true → false
??Default for null/undefinednull ?? "N/A" → "N/A"
?.Optional chaininguser?.address?.town
? :Ternary (conditional)age >= 18 ? "adult" : "minor"
...Spread / rest[...a, ...b]

String methods

Strings never change; these methods return new values. See Strings.

Method / propertyDescriptionExample → result
lengthNumber of characters"Lamu".length → 4
at(i)Character at index (negative counts from end)"Lamu".at(-1) → "u"
toUpperCase()Upper case copy"kisii".toUpperCase() → "KISII"
toLowerCase()Lower case copy"KISII".toLowerCase() → "kisii"
trim()Remove spaces at both ends" hi ".trim() → "hi"
includes(s)Contains s?"Nairobi".includes("robi") → true
startsWith(s) / endsWith(s)Starts / ends with s?"0722".startsWith("07") → true
indexOf(s)Position of first match or -1"banana".indexOf("n") → 2
slice(a, b)Part from a up to (not incl.) b"Mombasa".slice(0, 3) → "Mom"
replace(a, b)Replace first match"a-a".replace("a", "b") → "b-a"
replaceAll(a, b)Replace every match"a-a".replaceAll("a", "b") → "b-b"
split(sep)Break into an array"a,b".split(",") → ["a", "b"]
padStart(n, c)Pad at the start to length n"7".padStart(3, "0") → "007"
repeat(n)Repeat n times"ha".repeat(2) → "haha"

Number and Math methods

See Numbers & Math.

MethodDescriptionExample → result
Number(x)Convert to a numberNumber("42") → 42
parseInt(s)Read a whole number from textparseInt("12px") → 12
parseFloat(s)Read a decimal number from textparseFloat("2.5kg") → 2.5
n.toFixed(d)Round to d decimals (string)(3.456).toFixed(2) → "3.46"
n.toLocaleString()Regional formatting(15000).toLocaleString("en-KE") → "15,000"
Number.isNaN(x)Is it NaN?Number.isNaN(NaN) → true
Number.isInteger(x)Is it a whole number?Number.isInteger(4) → true
Math.round(x)Nearest whole numberMath.round(2.5) → 3
Math.floor(x) / Math.ceil(x)Round down / upMath.ceil(2.1) → 3
Math.max(...) / Math.min(...)Largest / smallestMath.max(4, 9) → 9
Math.abs(x)Absolute valueMath.abs(-3) → 3
Math.random()Random number from 0 up to 10.7364…

Array methods

See Arrays and Array Methods.

MethodDescriptionChanges the array?
lengthNumber of items–
push(x) / pop()Add / remove at the endYes
unshift(x) / shift()Add / remove at the startYes
splice(i, n, ...items)Remove and/or insert itemsYes
sort(fn)Sort (pass (a, b) => a - b for numbers)Yes
reverse()Reverse the orderYes
slice(a, b)Copy part of the arrayNo
concat(arr)Join arrays into a new oneNo
join(sep)Join items into a stringNo
includes(x)Contains x?No
indexOf(x)Position of x or -1No
forEach(fn)Run fn for each itemNo
map(fn)New array of transformed itemsNo
filter(fn)New array of matching itemsNo
find(fn) / findIndex(fn)First matching item / its indexNo
some(fn) / every(fn)Any / all items match?No
reduce(fn, start)Combine items into one valueNo
Array.isArray(x)Is x an array?No

Object helpers

See Objects.

MethodDescription
Object.keys(obj)Array of property names
Object.values(obj)Array of property values
Object.entries(obj)Array of [key, value] pairs
{ ...obj }Shallow copy of an object
structuredClone(obj)Deep copy of an object
"key" in objDoes the property exist?
delete obj.keyRemove a property

JSON

See JSON.

MethodDescription
JSON.stringify(value)Convert a value to a JSON string
JSON.stringify(value, null, 2)Same, nicely indented
JSON.parse(text)Convert a JSON string to a value (throws on invalid JSON)

DOM and events

See The DOM and Events.

Method / propertyDescription
document.getElementById(id)Element with that id
document.querySelector(css)First element matching a CSS selector
document.querySelectorAll(css)All matching elements
el.textContentGet/set plain text
el.innerHTMLGet/set HTML content (trusted content only)
el.valueValue of a form field
el.style.propInline style, e.g. el.style.color
el.classList.add/remove/toggle(c)Change CSS classes
el.getAttribute(a) / el.setAttribute(a, v)Read / write an attribute
document.createElement(tag)Make a new element
parent.append(child)Add a child at the end
el.remove()Remove an element
el.closest(css)Nearest matching ancestor
el.addEventListener(type, fn)Run fn when the event happens
event.preventDefault()Stop the browser's default action
event.targetElement the event started on

Timers and promises

See Async JavaScript.

FunctionDescription
setTimeout(fn, ms)Run fn once after ms milliseconds
setInterval(fn, ms)Run fn every ms milliseconds
clearTimeout(id) / clearInterval(id)Cancel a timer
new Promise((resolve, reject) => …)Create a promise
promise.then(fn) / .catch(fn) / .finally(fn)React to a promise
Promise.all([...])Wait for all promises (fails if any fails)
Promise.allSettled([...])Wait for all promises, whatever happens

Try it: a quick reference check

Example JAVASCRIPT
const words = "  Karibu Skope Digital Academy  ".trim().split(" ");
console.log(words.length);
console.log(words.map((w) => w[0]).join(""));
console.log([5, 1, 10].sort((a, b) => a - b).join(","));
console.log(Math.ceil(9.01), (2 ** 10).toLocaleString("en-KE"));
Result
4
KSDA
1,5,10
10 1,024
Try it Yourself »
Sign in or create a free account to track progress, earn XP, badges and a certificate.