Learn these eleven functions and you can handle most everyday JavaScript work: transform data with map(), select it with filter(), locate one item with find(), run side effects with forEach(), accumulate results with reduce(), test conditions with some() and every(), check membership with includes(), copy portions with slice(), schedule work with setTimeout(), and request data with fetch().
“Essential” is a practical learning order, not an official JavaScript ranking. The right function depends on the result you need: an array, one value, a boolean, a side effect, or an asynchronous response.
How to choose the right function
| Need | Use | Returns |
|---|---|---|
| Transform every item | map() |
New array |
| Keep matching items | filter() |
New array |
| Get the first match | find() |
An item or undefined |
| Do something for each item | forEach() |
undefined |
| Combine items into one result | reduce() |
Accumulator value |
| 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 |
| Run code later | setTimeout() |
Timer handle |
| Make an HTTP request | fetch() |
Promise for a response |
JavaScript functions are first-class values: you can store them, pass them as arguments, and return them. Array methods use this feature by accepting callback functions. A function with no explicit return produces undefined, so always return the value you intend from callbacks used by map, filter, and similar methods.
1. map(): transform every element
Use map() when each input has a corresponding output. It calls your callback for each array element and returns a new array; the original array is not the place to put the transformed result.
Free tools Windows power users keep installed
One-click scans. No signup required.
#1 Best Overall
const prices = [10, 20, 35];
const withTax = prices.map(price => price * 1.2);
console.log(withTax); // [12, 24, 42]
If you need to remove items, use filter() instead. A callback that forgets return yields an array of undefined values.
2. filter(): select a collection
filter() keeps elements whose predicate returns a truthy value and returns a new array. It is the natural choice for a list of matches, including an empty list when nothing qualifies.
const users = [
{ name: "Ari", active: true },
{ name: "Bo", active: false },
{ name: "Cy", active: true }
];
const activeUsers = users.filter(user => user.active);
console.log(activeUsers.map(user => user.name)); // ["Ari", "Cy"]
Do not use filter() merely to perform an action; that obscures intent and creates an unnecessary array.
3. find(): retrieve one matching item
When you want the first item satisfying a condition, find() communicates that goal directly. It returns the item or undefined if no item matches.
Quick wins for a faster PC:
Scan for outdated or missing drivers - takes under a minuteDriver Scan →Repair Windows errors before they cause bigger problemsFix Now →Fix the driver behind crashes, sound loss and screen glitchesFind Drivers →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 undefined before reading properties from a possibly missing result. Use filter() when multiple matches matter.
4. forEach(): perform a side effect
forEach() invokes a callback for each item and returns undefined. Use it for explicit actions such as logging, updating a counter outside the callback, or sending values to another API.
Rank #2
const names = ["Ari", "Bo", "Cy"];
names.forEach((name, index) => {
console.log(`${index + 1}. ${name}`);
});
It is not a replacement for map(): returning from a forEach() callback does not build a new array. For asynchronous callbacks, use a deliberate promise pattern rather than assuming forEach() waits for each operation.
5. reduce(): accumulate a result
reduce() walks the array while carrying an accumulator. That accumulator can become a number, string, object, map, or another array.
const orders = [
{ total: 12 },
{ total: 8 },
{ total: 25 }
];
const grandTotal = orders.reduce((sum, order) => sum + order.total, 0);
console.log(grandTotal); // 45
Provide an initial value (the 0 above) so empty arrays and accumulator types behave predictably. Although powerful, reduce() can hide intent; choose map(), filter(), or a simple loop when that expresses the operation more clearly.
6. some(): test whether any item matches
some() returns true as soon as its predicate succeeds and otherwise returns false. It is useful for permission checks, validation, and feature detection.
const hasInactive = users.some(user => !user.active);
console.log(hasInactive); // true
The result is a boolean, not the matching item. Use find() when you need that item.
7. every(): test whether all items match
every() returns true only when every element passes the predicate.
Recommended Free Tools
const allHaveNames = users.every(user => user.name.length > 0);
console.log(allHaveNames); // true
This is valuable for form validation and invariants. An empty array has no counterexample, so every() returns true for it; decide whether that interpretation fits your validation rule.
8. includes(): check membership
Use includes() for a direct yes/no membership test on an array or a substring test on a string.
const roles = ["editor", "reviewer"];
console.log(roles.includes("editor")); // true
console.log("JavaScript".includes("Script")); // true
It answers “is this present?” rather than returning an index or element. For object arrays, compare a property with some() or locate the object with find().
9. slice(): copy a portion
slice(start, end) returns a selected portion and leaves the source array or string unchanged. The end position is excluded.
The Tool Desk
Outbyte Driver Updater FREEScan for outdated or missing drivers - takes under a minuteDriver Scan →Outbyte PC Repair FREEClear out junk files and repair common Windows errorsFree Scan →const letters = ["a", "b", "c", "d"];
const middle = letters.slice(1, 3);
console.log(middle); // ["b", "c"]
console.log(letters); // ["a", "b", "c", "d"]
console.log("frontend".slice(0, 5)); // "front"
Negative positions count from the end. Use slice() when you need a copy or view; use a mutating operation only when changing the original is intentional.
10. setTimeout(): schedule a later task
setTimeout() is a host-provided timer API, available in browsers and commonly in server runtimes. It schedules a callback no earlier than the requested delay; the callback still waits for currently running JavaScript and queued work.
Rank #4
console.log("start");
setTimeout(() => console.log("later"), 500);
console.log("end");
// start, end, later
The return value is a timer handle that can be passed to clearTimeout(). A timer is not a sleep function and does not pause the current call stack.
11. fetch(): request network data
fetch() is a Web API global that returns a promise. A fulfilled promise gives you a response object; it does not automatically mean the server returned a successful HTTP status. Check response.ok (or the status) before consuming the body, and remember that response.json() is asynchronous too.
async function loadUser() {
const response = await fetch("https://api.example.com/users/42");
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
const user = await response.json();
return user;
}
loadUser()
.then(user => console.log(user))
.catch(error => console.error("Request failed:", error));
Availability depends on the runtime and its version. In browsers, cross-origin requests also depend on the server’s CORS policy. Promise handlers run asynchronously, even when a promise is already fulfilled, so code after fetch() runs before the response handler.
When should you use map(), filter(), or reduce()?
- Choose
map()when every input becomes one output. - Choose
filter()when you need a subset and may keep several items. - Choose
reduce()when many inputs must become one accumulated value. - Choose
find()for one matching item,some()/every()for boolean tests, andforEach()for side effects.
Writing the intended result in plain language before choosing a method prevents many beginner mistakes: “I need an array of names” points to map(); “I need active users” to filter(); “I need the first active user” to find(); and “I need the total” to reduce().
Common mistakes and fixes
Expecting a return from forEach()
It returns undefined. Replace it with map() when a new array is the goal.
Forgetting to return from a callback
Use an expression body such as x => x * 2, or write an explicit return inside braces.
Do these 3 things before closing this tab:
1Clear out junk files and repair common Windows errors2Scan for outdated or missing drivers - takes under a minute3Repair Windows errors before they cause bigger problemsBest Value
Assuming fetch() rejects on HTTP errors
Network failures reject the promise; an HTTP 404 or 500 normally resolves with ok === false. Check the response before parsing.
Assuming timers run exactly on time
The delay is a minimum. Long-running synchronous work postpones the callback.
Mutating data accidentally
These methods return new arrays for their selected or transformed results, but object values inside are still references. Treat shared objects deliberately and avoid changing source data inside callbacks unless that side effect is intentional.
Or skip the browser setup
If your goal is to generate a screenshot from JavaScript rather than manage a headless browser, ScreenshotNeo provides a single HTTP call. It accepts cookie and consent banners, then removes more than 60 known consent platforms, newsletter popups, and chat widgets before capture. Bot checks, blank pages, failed loads, timeouts, and cache hits are not billed, and response headers identify the page verdict and billing status.
JavaScript with the API:
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
const image = await res.arrayBuffer();
// save image to your runtime's preferred file or object storage
See the ScreenshotNeo documentation for response formats and options. Equivalent calls are available in cURL and Python:
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
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)
The API also supports full-page and element captures, dark mode, device presets, custom CSS and JavaScript, waits, blocking rules, headers, cookies, geolocation, PDFs, caching, signed links, asynchronous jobs, bulk capture, and an MCP server for AI agents. One thousand screenshots per month are free with no card; paid plans start at $5 for 3,000. Create a free ScreenshotNeo account.
Frequently Asked Questions
Are these functions part of the JavaScript language itself?
Most listed array methods are standard built-in methods. setTimeout() is supplied by the host environment, and fetch() is a Web API global whose availability depends on the runtime.
Why do promise callbacks run later?
Promise handlers are scheduled asynchronously through the microtask queue, so even an already-fulfilled promise does not run its handler inline with the current statement.
What should I learn after these eleven functions?
Next, learn objects and modules, error handling, async/await, DOM or server APIs for your target runtime, and testing. Those topics let you combine these functions safely in larger programs.
Quick Recap
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.

