Lessons · JavaScript · slice()
A window onto an array or string
slice(start, end) takes items from start up to but not including end; negative numbers count from the end.
Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.
What it is for
First N, last N, everything but the header, a page of results.
How to think about it
From which position, up to which? Say it as a range: 'from 2 up to 5'. End is exclusive, so length is end minus start. Leave end off for 'to the end'.
Worked example
const d = ["mon", "tue", "wed", "thu"];Positions 0 to 3.
d.slice(1, 3)["tue", "wed"].
d.slice(-2)["wed", "thu"].
"hello".slice(0, 2)"he": strings too.
Your turn
Everything except the first item.
const rest = items.slice();
Solve one with the tests running
The trap
There is no step argument. Every-other-item needs filter((_, i) => i % 2 === 0).
Practise slice() on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.