Technical skill practice

JavaScript slice: Extract an Array Window Without Editing It

Use slice when you want an array segment without deleting elements from the source. The start is included and the end is excluded. The new array container still shares object elements with the original.

The task

Create the second two-item window from four page records. Then inspect the final item using a negative start and change a field through the extracted window to reveal reference sharing.

Runnable Node 22 example

const assert = require('node:assert/strict');

const pages = [{id: 1}, {id: 2}, {id: 3}, {id: 4}];
const window = pages.slice(2, 4);
assert.deepEqual(window.map(page => page.id), [3, 4]);
assert.equal(pages.length, 4);
assert.notEqual(window, pages);
assert.equal(window[0], pages[2]);
assert.deepEqual(pages.slice(-1).map(page => page.id), [4]);
assert.deepEqual(pages.slice(3, 2), []);
window[0].id = 30;
assert.equal(pages[2].id, 30);
console.log(JSON.stringify(window.map(page => page.id)));

Expected output and explanation

The slice starts at index two and stops before index four, so it initially contains IDs three and four. A reversed range produces an empty array; it does not automatically reverse the data. A start of −1 selects the last element.

Changing window[0].id also changes the third source record because both arrays point to that object. This does not mean slice inserted or removed a source element: the source length remains four. Container independence and nested-record independence are separate properties.

Output from the example

[30,4]

Pitfall to check

Use splice for a deliberate edit and a separate cloning strategy when nested records must be independent. Pagination also needs a defined page-number convention; this example uses zero-based array offsets directly, not a user-facing page-number formula.

Questions, answered

Can slice extract part of a string too?

Strings have a separate slice method with similar bounds. This example tests arrays and shared object elements; strings do not expose that same mutable-record issue.

Sources and examples

ResumizeAI team. Examples are fictional teaching material, not customer results. Replace sample details with your own facts.

Your experience. A complete resume.

Build in Resumize with ATS-friendly templates, guided editing and a live preview. Start free, then upgrade when you need more.

Free account required. Free-plan PDF exports include a watermark.