← All Notes

Javascript methods cheat sheet

Quick decision guide

Need a boolean?         → some / every / includes
Need one item?          → find
Need many items?        → filter
Need transformed data?  → map
Need an action only?    → forEach
Need part of an array?  → slice
Need one string?        → join

A more direct version:

.some()       → Does some item match?
.every()      → Does every item match?
.find()       → Find the first matching item.
.filter()     → Keep all matching items.
.map()        → Turn each item into something else.
.includes()   → Does it include this value?
.forEach()    → Do something for each item.

Array methods

.map()

Question: Turn every item into something else?

Returns a new array.

const teachers = [
  { name: "Anna" },
  { name: "John" },
]

const names = teachers.map(
  (teacher) => teacher.name
)

Result:

["Anna", "John"]

Mental translation:

Map each teacher to their name.

This is especially common when rendering data:

navItems.map((item) => (
  <a href={item.href}>
    {item.label}
  </a>
))

Mental translation:

Map each nav item to an <a> element.

Use .map() when every input item should become an output item.


.filter()

Question: Which items should I keep?

Returns a new array containing all matching items.

const reviews = [
  { rating: 5 },
  { rating: 3 },
  { rating: 5 },
]

const fiveStarReviews = reviews.filter(
  (review) => review.rating === 5
)

Result:

[
  { rating: 5 },
  { rating: 5 },
]

Mental translation:

Filter the reviews to only 5-star reviews.

Another practical example:

const validReviews = reviews.filter(
  (review) =>
    review.text.trim() &&
    review.authorName.trim()
)

Mental translation:

Keep only reviews that have text and an author name.


.find()

Question: Find me the first item that matches?

Returns the actual item, or undefined if nothing matches.

const programs = [
  { id: "preschool", title: "Preschool" },
  { id: "summer-camp", title: "Summer Camp" },
]

const program = programs.find(
  (program) => program.id === "summer-camp"
)

Result:

{
  id: "summer-camp",
  title: "Summer Camp"
}

Mental translation:

Find the program whose ID is summer-camp.

Use .find() when I need one matching item.


.some()

Question: Does some item match?

Returns true or false.

const children = [
  { href: "/philosophy" },
  { href: "/teachers" },
  { href: "/contact" },
]

const isCurrent = children.some(
  (child) => child.href === "/teachers"
)

Result:

true

Mental translation:

Does some child match /teachers?

A real navigation example:

const isCurrent = item.children.some(
  (child) => child.href === currentPath
)

Mental translation:

Does some child match the current path?

This is useful when a parent item should become active because one of its children is active.


.includes()

Question: Does this include this exact value?

Returns true or false.

const roles = [
  "admin",
  "editor",
  "user",
]

const canEdit = roles.includes("editor")

Result:

true

Mental translation:

Do the roles include editor?

For simple values, .includes() is usually clearer than .some().

Prefer:

roles.includes("editor")

over:

roles.some(
  (role) => role === "editor"
)

But for objects, use .some():

users.some(
  (user) => user.id === 123
)

.forEach()

Question: Do something for each item?

Runs an action for every item.

const names = [
  "Anna",
  "John",
]

names.forEach((name) => {
  console.log(name)
})

Mental translation:

For each name, log it.

The important difference:

.map()

Transform each item and return a new array.

.forEach()

Just do something for each item.

Example:

const doubled = [1, 2, 3].map(
  (number) => number * 2
)

Result:

[2, 4, 6]

But:

[1, 2, 3].forEach(
  (number) => console.log(number)
)

just performs an action.


.every()

Question: Does every item match?

Returns true or false.

const ages = [
  18,
  21,
  30,
]

const allAdults = ages.every(
  (age) => age >= 18
)

Result:

true

Mental translation:

Is every age at least 18?

Compare:

ages.some(
  (age) => age >= 18
)

Is some age at least 18?

ages.every(
  (age) => age >= 18
)

Is every age at least 18?

A practical form example:

const allComplete = fields.every(
  (field) => field.value.trim()
)

Mental translation:

Does every field have a value?


.slice()

Question: Give me a slice of this array?

Returns part of an array without changing the original.

const programs = [
  "Preschool",
  "After School",
  "Summer Camp",
  "Nature Club",
]

const firstTwo = programs.slice(0, 2)

Result:

[
  "Preschool",
  "After School",
]

Mental translation:

Slice from position 0 up to, but not including, position 2.

A common example:

reviews.slice(0, 3)

Mental translation:

Give me the first three reviews.


.join()

Question: Join all array items into one string?

const days = [
  "M",
  "W",
  "F",
]

const schedule = days.join(" · ")

Result:

M · W · F

Mental translation:

Join the days using · between them.


.findIndex()

Question: Where is the first matching item?

Returns the item’s index, or -1 if nothing matches.

const programs = [
  "Preschool",
  "After School",
  "Summer Camp",
]

const index = programs.findIndex(
  (program) => program === "After School"
)

Result:

1

Mental translation:

Find the index of After School.

Remember that array indexes start at 0.


.at()

Question: Give me the item at this position?

const programs = [
  "Preschool",
  "After School",
  "Summer Camp",
]

programs.at(0)

Result:

"Preschool"

A particularly useful case:

programs.at(-1)

Result:

"Summer Camp"

Mental translation:

Give me the last item.

This is clearer than:

programs[programs.length - 1]

.sort()

Question: Sort these items?

Important: .sort() changes the original array.

const names = [
  "Zoe",
  "Anna",
  "John",
]

names.sort()

Result:

[
  "Anna",
  "John",
  "Zoe",
]

For numbers:

const prices = [
  100,
  20,
  5,
]

prices.sort(
  (a, b) => a - b
)

Result:

[
  5,
  20,
  100,
]

Mental translation:

a - b

Sort smallest to largest.

b - a

Sort largest to smallest.

Be careful with this:

[100, 20, 5].sort()

Default sorting compares values like strings, which is often not what I want for numbers.


.reduce()

Question: Reduce the entire array to one final value?

Useful, but often overused.

const prices = [
  10,
  20,
  30,
]

const total = prices.reduce(
  (sum, price) => sum + price,
  0
)

Result:

60

Mental translation:

Reduce all prices into one total.

This part:

(sum, price) => sum + price

means:

Take the running sum and add the current price.

And this:

0

means:

Start at zero.

I should not reach for .reduce() just because it looks clever. If .map(), .filter(), .find(), or a simple loop is easier to understand, use that instead.


Array methods that change the original array

These are common, but I should remember that they mutate the array.

.push()

Question: Add an item to the end?

const programs = [
  "Preschool",
]

programs.push(
  "Summer Camp"
)

Now:

[
  "Preschool",
  "Summer Camp",
]

Mental translation:

Push this item onto the end.


.pop()

Question: Remove the last item?

const programs = [
  "Preschool",
  "Summer Camp",
]

const removed = programs.pop()

removed is:

"Summer Camp"

The array is now:

[
  "Preschool",
]

Mental translation:

Pop the last item off.


.shift()

Question: Remove the first item?

const programs = [
  "Preschool",
  "Summer Camp",
]

programs.shift()

The array is now:

[
  "Summer Camp",
]

.unshift()

Question: Add an item to the beginning?

const programs = [
  "Summer Camp",
]

programs.unshift(
  "Preschool"
)

Now:

[
  "Preschool",
  "Summer Camp",
]

String methods

.trim()

Question: Remove surrounding whitespace?

const name = "   Anna   "

name.trim()

Result:

Anna

Mental translation:

Remove whitespace from the beginning and end.

This is particularly useful for validation:

review.text.trim()

For example:

"   ".trim()

becomes:

""

An empty string is falsy, so this is useful when checking whether meaningful text exists.


.includes()

Question: Does this string contain this text?

const pathname = "/programs/preschool"

pathname.includes("programs")

Result:

true

Mental translation:

Does the pathname include programs?


.startsWith()

Question: Does this string start with this?

const pathname = "/programs/preschool"

pathname.startsWith("/programs")

Result:

true

Mental translation:

Does the pathname start with /programs?

A practical route example:

const isProgramsSection =
  currentPath.startsWith("/programs/")

.split()

Question: Split this string into an array?

const tags = "astro,css,javascript"

tags.split(",")

Result:

[
  "astro",
  "css",
  "javascript",
]

Mental translation:

Split wherever there is a comma.

Another example:

const fullName = "John Smith"

fullName.split(" ")

Result:

[
  "John",
  "Smith",
]

.replace()

Question: Replace this text with something else?

const title = "Hello World"

title.replace(
  "World",
  "Astro"
)

Result:

Hello Astro

For simple string replacement, .replace() replaces the first matching occurrence.


.replaceAll()

Question: Replace every match?

const slug = "summer camp program"

slug.replaceAll(
  " ",
  "-"
)

Result:

summer-camp-program

Mental translation:

Replace all spaces with hyphens.


.endsWith()

Question: Does this string end with this?

const filename = "photo.webp"

filename.endsWith(".webp")

Result:

true

Mental translation:

Does the filename end with .webp?


.toLowerCase()

Question: Make everything lowercase?

"Summer Camp".toLowerCase()

Result:

summer camp

Useful for normalized comparisons:

input.toLowerCase() === "yes"

.toUpperCase()

Question: Make everything uppercase?

"faq".toUpperCase()

Result:

FAQ

Object methods

Object.entries()

Question: Give me each key and value together?

const schedule = {
  start: "9:00",
  end: "3:00",
}

Object.entries(schedule)

Result:

[
  ["start", "9:00"],
  ["end", "3:00"],
]

Mental translation:

Turn the object into key/value pairs.

This becomes especially useful with .map():

Object.entries(schedule).map(
  ([key, value]) => `${key}: ${value}`
)

Result:

[
  "start: 9:00",
  "end: 3:00",
]

Object.keys()

Question: Give me all property names?

const teacher = {
  name: "Anna",
  role: "Teacher",
  age: 32,
}

Object.keys(teacher)

Result:

[
  "name",
  "role",
  "age",
]

Mental translation:

Give me the keys of this object.


Object.values()

Question: Give me all property values?

Object.values(teacher)

Result:

[
  "Anna",
  "Teacher",
  32,
]

Mental translation:

Give me the values of this object.


Object.fromEntries()

Question: Build an object from key/value pairs?

const entries = [
  ["name", "Anna"],
  ["role", "Teacher"],
]

Object.fromEntries(entries)

Result:

{
  name: "Anna",
  role: "Teacher",
}

Mental translation:

Build an object from entries.

It is essentially the reverse of:

Object.entries()

Other useful methods

Array.isArray()

Question: Is this actually an array?

Array.isArray(
  ["a", "b"]
)

Result:

true

But:

Array.isArray(
  "a,b"
)

Result:

false

Number.isFinite()

Question: Is this a real finite number?

const safeInterval =
  Number.isFinite(interval) &&
  interval >= 1000
    ? interval
    : 3500

Mental translation:

Is interval actually a valid finite number and large enough to use?


JSON.stringify()

Question: Turn JavaScript data into JSON text?

const user = {
  name: "Anna",
  age: 30,
}

JSON.stringify(user)

Result:

{"name":"Anna","age":30}

A practical HTML data attribute example:

data-reviews={
  JSON.stringify(validReviews)
}

Mental translation:

Turn the reviews array into text so it can be stored in an HTML attribute.


JSON.parse()

Question: Turn JSON text back into JavaScript data?

const json =
  '{"name":"Anna","age":30}'

const user = JSON.parse(json)

Result:

{
  name: "Anna",
  age: 30,
}

Mental translation:

Parse the JSON string back into JavaScript data.


Common combinations

The methods become easier to remember when I think about actual problems.

Find one matching program

const program = programs.find(
  (program) =>
    program.id === currentId
)

Mental translation:

Find the program matching the current ID.


Check whether any child is current

const isCurrent = item.children.some(
  (child) =>
    child.href === currentPath
)

Mental translation:

Does some child match the current path?


Get only valid reviews

const validReviews = reviews.filter(
  (review) =>
    review.text.trim() &&
    review.authorName.trim()
)

Mental translation:

Filter reviews to those with text and an author name.


Get only teacher names

const teacherNames = teachers.map(
  (teacher) => teacher.name
)

Mental translation:

Map each teacher to their name.


Check whether every field is complete

const allComplete = fields.every(
  (field) => field.value.trim()
)

Mental translation:

Does every field have a value?


Check whether some field is empty

const hasEmptyField = fields.some(
  (field) => !field.value.trim()
)

Mental translation:

Does some field have no value?


Get all 5-star reviews

const fiveStarReviews = reviews.filter(
  (review) => review.rating === 5
)

Mental translation:

Filter reviews to only those rated 5.


Transform reviews into review cards

Conceptually:

reviews.map(
  (review) =>
    renderReviewCard(review)
)

Mental translation:

Map each review to a review card.


Mutation warning

Some methods change the original array:

.push()
.pop()
.shift()
.unshift()
.sort()
.splice()
.reverse()

Others return new arrays without changing the original:

.map()
.filter()
.slice()
.concat()

And some mainly inspect or search:

.some()
.every()
.find()
.findIndex()
.includes()

This matters when the same data is reused in multiple places.


The methods I should learn first

For my own frontend work, this is the practical priority.

First

.map()
.filter()
.find()
.some()
.includes()
.forEach()

Mental model:

map      → transform each item
filter   → keep matching items
find     → get the first matching item
some     → does some item match?
includes → does it include this value?
forEach  → do something for each item

Next

.every()
.slice()
.join()
.findIndex()
.trim()
.startsWith()
.split()

Mental model:

every      → does every item match?
slice      → give me part of it
join       → combine items into a string
findIndex  → where is the matching item?
trim       → remove surrounding whitespace
startsWith → does it start with this?
split      → break a string into an array

Learn when needed

.reduce()
.sort()
Object.entries()
Object.fromEntries()

These are useful, but I do not need to force them into code when a simpler method is easier to understand.


Final mental shortcut

When looking at an array, ask what result I actually need:

Need true or false?
→ some / every / includes

Need one item?
→ find

Need several matching items?
→ filter

Need to transform every item?
→ map

Need to perform an action?
→ forEach

Need part of the array?
→ slice

Need one combined string?
→ join

That is usually enough to point me toward the right method.

Given the code you actually write, I would memorize these first:

Tier 1 — use constantly

.map()
.filter()
.find()
.some()
.includes()

Think:

map      → transform each item
filter   → keep matching items
find     → get first matching item
some     → does some item match?
includes → does it include this value?

Tier 2 — very useful

.every()
.findIndex()
.slice()
.join()
.trim()
.startsWith()
.split()

Think:

every      → does every item match?
findIndex  → where is the matching item?
slice      → give me part of it
join       → combine items into a string
trim       → remove surrounding whitespace
startsWith → does it start with this?
split      → break string into an array

Tier 3 — learn when needed

.reduce()
.sort()
Object.entries()
Object.fromEntries()
.flat()
.flatMap()

I would especially not force yourself to use .reduce() early. .some(), .find(), .filter(), and .map() are much easier to reason about and cover a huge amount of real web-development work.

Ultra-short reference

.some()       → Does some item match?
.every()      → Does every item match?
.find()       → Find the first matching item.
.filter()     → Keep all matching items.
.map()        → Turn each item into something else.
.forEach()    → Do something for each item.
.includes()   → Does it include this value?
.findIndex()  → Where is the matching item?
.slice()      → Give me a section.
.join()       → Join items into a string.
.sort()       → Sort the items.
.reduce()     → Reduce everything to one result.

.trim()       → Remove surrounding whitespace.
.split()      → Split string into an array.
.replace()    → Replace text.
.startsWith() → Does it start with this?
.endsWith()   → Does it end with this?
.includes()   → Does it contain this?

Object.keys()    → Give me the property names.
Object.values()  → Give me the property values.
Object.entries() → Give me key/value pairs.

For your work specifically, the most valuable mental pattern is probably:

Need a boolean?       → some / every / includes
Need one item?        → find
Need many items?      → filter
Need transformed data?→ map
Need an action only?  → forEach