OpenViSTAI · Agents · Blockchain · Crypto
Menu

OPENVIST LEARN · FREE LESSONS

Arrays and shared references

Read and change ordered values while noticing when two names share one array.

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

By the end of this lesson

Append a value and make a shallow copy deliberately.

Before you start

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

Three words to know

Array
An ordered indexed collection.
Reference
A way a name refers to an object rather than duplicating it.
Shallow copy
A new outer container that still shares nested objects.

1. Work with ordered items

Arrays preserve order and allow duplicates. push changes an array; join returns a display string. The length is the number of indexed positions, and reading outside the array normally returns undefined. Do not assume an absent item has a useful default.

A topic listJAVASCRIPT · Node.js · save as lesson.mjs
const topics = ["read", "test"];
topics.push("review");
console.log(topics.length);
console.log(topics[0]);
console.log(topics.join(" → "));
What you should see · example output
3
read
read → test → review

2. Assignment shares the array

A second name does not clone the first array. slice creates a new outer array, so appending to it does not append to the original. Nested objects inside a shallow copy would still be shared.

Alias and copyJAVASCRIPT · Node.js · save as lesson.mjs
const original = ["a"];
const alias = original;
const independent = original.slice();
alias.push("b");
console.log(JSON.stringify(original));
console.log(JSON.stringify(independent));
What you should see · example output
["a","b"]
["a"]

3. Separate mutation from transformation

A transformation that returns a new array is easier to reuse when the original must remain available. Later lessons introduce map and filter. Sorting is an important exception to notice: sort mutates its array, and its default order treats elements as strings. Numeric sorting needs an explicit comparison rule.

YOUR TURN

A small check before you continue

Copy [1, 2], append 3 only to the copy and print both with JSON.stringify.

Show a suggested answer

Use const copy = original.slice(); copy.push(3). The original remains [1,2] and the copy becomes [1,2,3]. This is only a shallow copy.

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.