Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

If you are learning everyday JavaScript, start with these 11 functions and methods: map(), filter(), find(), forEach(), reduce(), some(), every(), includes(), slice(), setTimeout(), and fetch(). Together they cover transforming data, selecting records, checking conditions, producing side effects, accumulating results, delaying work, and calling services.

The examples below run in a modern browser console. Most array methods return a new value and leave the original array unchanged; always read the return type before choosing a method.

How to choose the right function

Goal Use Typical result
Transform every item map() New array
Keep matching items filter() New array
Get the first match find() One item or undefined
Run an action for each item forEach() undefined
Combine values reduce() Accumulator of your choice
Ask whether any item matches some() Boolean
Ask whether all items match every() Boolean
Check for a value or substring includes() Boolean
Copy a range slice() New array or string
Schedule later work setTimeout() Timer handle
Request a resource fetch() Promise

JavaScript functions are first-class values: you can store them, pass them as arguments, and return them. That is why array methods accept callback functions. A function without an explicit return produces undefined, and an omitted argument is also undefined.

1. map(): transform every element

Use map() when each input item has one corresponding output item. It calls your callback for each array element and returns a new array.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
const prices = [10, 15, 20];
const withTax = prices.map(price => price * 1.2);
console.log(withTax); // [12, 18, 24]
console.log(prices);  // [10, 15, 20]

The callback can receive the value, index, and source array. Return the value you want in the new array; braces without a return statement produce undefined entries.

const labels = prices.map((price, index) => {
  return `Item ${index + 1}: $${price}`;
});

2. filter(): select a subset

filter() keeps elements for which the predicate returns a truthy value. The result is a new array and can contain zero, one, or many items.

const users = [
  { name: 'Ari', active: true },
  { name: 'Bo', active: false },
  { name: 'Cy', active: true }
];
const activeUsers = users.filter(user => user.active);
console.log(activeUsers); // Ari and Cy

Use filter() for a collection. If you need only the first matching record, use find() instead.

3. find(): retrieve the first match

find() stops at the first element whose predicate is truthy and returns that element. If no element matches, it returns undefined.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
const account = users.find(user => user.name === 'Bo');
console.log(account); // { name: 'Bo', active: false }

const missing = users.find(user => user.name === 'De');
console.log(missing); // undefined

Check for the no-match case before reading properties. For a boolean-only question, some() communicates intent more clearly.

4. forEach(): perform a side effect

Use forEach() when you want an action for every item, such as logging, updating the DOM, or sending metrics—not a transformed array.

const names = ['Ari', 'Bo', 'Cy'];
names.forEach((name, index) => {
  console.log(`${index}: ${name}`);
});

It returns undefined. A return inside the callback does not stop the outer iteration, and break cannot be used there. Use a for...of loop when you need early exit or sequential await.

5. reduce(): accumulate one result

reduce() carries an accumulator through the array and can produce a number, string, object, map, or another array. Supplying an initial value makes behavior explicit, including for an empty array.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
const lineItems = [
  { price: 12, quantity: 2 },
  { price: 5, quantity: 3 }
];
const total = lineItems.reduce(
  (sum, item) => sum + item.price * item.quantity,
  0
);
console.log(total); // 39

Do not reach for reduce() merely because it is powerful. map(), filter(), and find() are usually clearer when the intent is transform, select, or locate. For a lookup object, an accumulator is useful:

const byName = users.reduce((lookup, user) => {
  lookup[user.name] = user;
  return lookup;
}, {});

6. some(): test whether any item passes

some() returns true as soon as one callback result is truthy; otherwise it returns false. It expresses an “at least one” question and can stop early.

const hasInactive = users.some(user => !user.active);
console.log(hasInactive); // true

Unlike find(), it returns only a boolean, not the matching object.

7. every(): test whether all items pass

every() returns true only when every element satisfies the predicate. It also stops as soon as a failure is found.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
const allHaveNames = users.every(user => user.name.length > 0);
console.log(allHaveNames); // true

An empty array returns true: there is no element that violates the condition. If an empty collection should fail validation, check its length separately.

8. includes(): check membership

For arrays, includes() answers whether a value is present. For strings, it checks for a substring. The result is a boolean.

const roles = ['admin', 'editor', 'viewer'];
console.log(roles.includes('editor')); // true
console.log('JavaScript'.includes('Script')); // true

It checks values, not object shape. A separately created object with identical properties is not the same reference as the object in an array. Use some() or find() for property-based checks.

9. slice(): copy a range without changing the source

slice(start, end) copies from the start index up to, but not including, the end index. Negative indexes count from the end. Omitting end copies through the remainder.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
const months = ['Jan', 'Feb', 'Mar', 'Apr'];
console.log(months.slice(1, 3)); // ['Feb', 'Mar']
console.log(months.slice(-2));  // ['Mar', 'Apr']
console.log(months);            // unchanged

For a shallow copy of an array, use slice() with no arguments. Nested objects are still shared references, so changing a nested object changes it in both arrays.

10. setTimeout(): schedule a later callback

setTimeout(callback, delay) asks the host environment to run a callback after at least the requested delay. It is a timer API supplied by browsers and common JavaScript runtimes, not a core language function, and the delay is not a precise execution deadline.

console.log('start');
setTimeout(() => console.log('later'), 0);
console.log('end');
// start, end, later

Even a zero-millisecond timer waits until current synchronous work finishes. Save the returned handle to cancel it:

const timerId = setTimeout(() => {
  console.log('This may not run');
}, 1000);
clearTimeout(timerId);

For a promise-friendly delay, wrap it:

const delay = ms => new Promise(resolve => setTimeout(resolve, ms));
await delay(500);

11. fetch(): make an HTTP request

fetch() is a Web API global that returns a promise. Availability differs by runtime and version, so check your browser or server environment. A fulfilled promise gives a Response; it does not automatically mean the HTTP status is successful.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
async function loadUser() {
  const response = await fetch('https://example.com/api/user');
  if (!response.ok) {
    throw new Error(`HTTP ${response.status}`);
  }
  const data = await response.json();
  return data;
}

loadUser()
  .then(user => console.log(user))
  .catch(error => console.error(error));

response.json() is asynchronous and returns another promise. Handle network failures with try...catch or a rejected-promise handler. Add an abort signal when a request must have a deadline:

async function fetchWithTimeout(url, ms = 8000) {
  const controller = new AbortController();
  const timer = setTimeout(() => controller.abort(), ms);
  try {
    const response = await fetch(url, { signal: controller.signal });
    if (!response.ok) throw new Error(`HTTP ${response.status}`);
    return await response.json();
  } finally {
    clearTimeout(timer);
  }
}

Promise callbacks run asynchronously through the microtask queue, and then() returns another promise, allowing chains. Prefer async/await for readable sequential flows and always handle rejection.

Practical combinations

Filter, then transform

const visibleNames = users
  .filter(user => user.active)
  .map(user => user.name);

Find, then handle absence

const editor = users.find(user => user.role === 'editor');
if (editor) console.log(editor.name);

Validate before submitting

const valid = lineItems.every(item => item.quantity > 0);
const hasFreeItem = lineItems.some(item => item.price === 0);

Common mistakes and fixes

  • Expecting forEach() to return an array: use map() for returned values.
  • Using filter() for one record: use find() and handle undefined.
  • Forgetting a return in a block callback: write return value; or use an expression body.
  • Assuming fetch() rejects on a 404: test response.ok yourself.
  • Mutating while expecting a copy: slice() is shallow; nested references remain shared.
  • Using timers for exact scheduling: timers wait until the event loop is free; they do not interrupt running code.
  • Reducing without an initial value: provide one, especially when the input may be empty.
  • Using includes() on objects: compare a property with some() or locate it with find().
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Or skip the browser setup

If your goal is to capture a page while practicing fetch(), ScreenshotNeo provides a website screenshot API and MCP server. It accepts consent banners like a visitor and removes more than 60 known consent platforms, newsletter popups, and chat widgets before capture; bot checks, blank pages, timeouts, failed loads, and cache hits are not billed, with the result identified by X-Page-Verdict and X-Billed headers. AI agents can use its MCP tools—take_screenshot, get_page_info, and capture_pdf.

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp

See the ScreenshotNeo documentation for parameters. The same request in Python:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
import requests
r = requests.get("https://api.screenshotneo.com/v1/shot", params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"}, timeout=90)
open("shot.webp", "wb").write(r.content)

And in Node.js:

const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const buffer = Buffer.from(await res.arrayBuffer());
require('fs').writeFileSync('shot.webp', buffer);

ScreenshotNeo includes 1,000 screenshots a month free with no card; paid plans start at $5 for 3,000. Create a free ScreenshotNeo account.

FAQ

Are these functions all part of the JavaScript language?

No. Array methods are built-in object methods, while setTimeout() and fetch() are host-provided APIs whose availability depends on the runtime.

Which three array methods should a beginner learn first?

Learn map() for transforming, filter() for selecting, and find() for retrieving one match. Add reduce() after you are comfortable identifying the desired output.

Can these methods change the original array?

The methods shown here return values for their operations; callbacks can still mutate objects or other external state. Keep callbacks free of unintended mutations when predictable code matters.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Frequently Asked Questions

Are these functions all part of the JavaScript language?

No. Array methods are built-in object methods, while setTimeout() and fetch() are host-provided APIs whose availability depends on the runtime.

Which three array methods should a beginner learn first?

Learn map() for transforming, filter() for selecting, and find() for retrieving one match. Add reduce() after you are comfortable identifying the desired output.

Can these methods change the original array?

The methods shown here return values for their operations; callbacks can still mutate objects or other external state. Keep callbacks free of unintended mutations when predictable code matters.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.