OpenViSTAI · Agents · Blockchain · Crypto
Menu

OPENVIST LEARN · FREE LESSONS

Callbacks, map, filter and numeric sorting

Pass a small function to an array operation and understand whether the input changes.

Lesson 14 of 25 · About 20 minutes · Beginner · English

By the end of this lesson

Transform and filter a list while retaining the original.

Before you start

  • Node.js 24 with a terminal and plain-text editor; the browser-only lesson is labelled separately.
  • Complete lesson 13 or be comfortable with its examples.

Three words to know

Callback
A function supplied for another operation to call.
Arrow function
A compact function expression written with =>.
Transformation
A rule that produces a new representation from existing data.

1. Map each value to another value

map calls its callback for each item and returns a new array. The concise arrow below returns the expression after =>. If you use a brace body instead, add return explicitly when a value is needed.

Double small countsJAVASCRIPT · Node.js · save as lesson.mjs
const values = [1, 2, 3];
const doubled = values.map(value => value * 2);
console.log(JSON.stringify(doubled));
console.log(JSON.stringify(values));
What you should see · example output
[2,4,6]
[1,2,3]

2. Filter using a boolean rule

filter keeps items whose callback returns a truthy value. It does not modify the original outer array, but retained objects are still shared references. Keep callback side effects small so the rule stays predictable.

Select open recordsJAVASCRIPT · Node.js · save as lesson.mjs
const records = [{ status: "open" }, { status: "closed" }];
const open = records.filter(record => record.status === "open");
console.log(open.length);
What you should see · example output
1

3. Numeric sorting needs a numeric comparison

The default sort converts items to strings for comparison. A numeric comparator fixes that rule. sort mutates its array, so copy first if you need the original unchanged. Arrow callbacks also avoid introducing a new dynamic this, but ordinary functions are still useful when their receiver behaviour is intended.

Sort a copy numericallyJAVASCRIPT · Node.js · save as lesson.mjs
const sizes = [10, 2, 1];
const sorted = [...sizes].sort((a, b) => a - b);
console.log(JSON.stringify(sorted));
console.log(JSON.stringify(sizes));
What you should see · example output
[1,2,10]
[10,2,1]

YOUR TURN

A small check before you continue

What does values.map(value => { value * 2; }) return for [1,2]?

Show a suggested answer

An array of two undefined values, because the brace body has no return. Use value => value * 2 or value => { return value * 2; }.

Sources and scope

Documentation and examples reviewed 2026-10-18. Provider screens, package versions and output wording can differ. Examples show expected outcomes; they are not a claim that OpenViST connected to your server or verified your setup.