Taking the Next Three Weeks With slice()

Monday’s rotation leaves Dev, Sam, Ines, Kofi, Bea, and Marta in the queue. The team channel needs the names for the next three weeks, and the leave planner wants the queue in reverse order. Creating either view must leave the original rota unchanged. JavaScript replaces Python’s slice syntax with methods. Check whether each method changes your array.

Take a Range With .slice()

For the channel post, Python’s rota[:3] becomes rota.slice(0, 3). The array method .slice() follows the string method’s rules: the end is excluded, negative positions count from the end, and positions beyond the array are clipped. These familiar slices become method calls:

Python JavaScript Result
rota[:3] rota.slice(0, 3) First three names
rota[3:] rota.slice(3) From position three onward
rota[-2:] rota.slice(-2) Last two names
rota[:] rota.slice() All names in a new array

Arguments are positional, so to take the first three items, pass 0 as the start and 3 as the end. Omitting the end takes everything from the start onward. Omitting both makes a copy, a new array containing the same items. You’ll learn more about why copying matters later.

Locked learning resources

Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Locked learning resources

The full lesson is for members only. Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Become a Member to join the conversation.