Menu
Coddy logo textTech

Spread Operator with Arrays

Part of the Introduction To TypeScript section of Coddy's JavaScript journey — lesson 20 of 73.

JavaScript's spread operator (...) is a powerful feature that works seamlessly with TypeScript's typed arrays. When you use the spread syntax to combine arrays, TypeScript automatically infers the correct type for the resulting array, maintaining full type safety throughout the operation.

The spread operator allows you to "spread out" the elements of an array into individual elements. When combining typed arrays, you simply use the spread syntax inside square brackets to create a new array:

let firstNumbers: number[] = [1, 2, 3];
let secondNumbers: number[] = [4, 5, 6];
let combined: number[] = [...firstNumbers, ...secondNumbers];
// Result: [1, 2, 3, 4, 5, 6]

TypeScript is smart enough to understand that when you spread two number[] arrays together, the result is also a number[]. This type inference works with any array type, whether it's strings, booleans, or custom objects.

You can even mix the spread operator with individual elements:

let scores: number[] = [85, 92];
let allScores: number[] = [100, ...scores, 78];
// Result: [100, 85, 92, 78]

This approach creates a new array without modifying the original arrays, which is particularly useful when working with immutable data patterns. The spread operator provides a clean, readable way to combine arrays while preserving TypeScript's type checking benefits.

challenge icon

Challenge

Easy

Create two typed arrays: firstScores containing the numbers 85, 92, and 78, and secondScores containing the numbers 88, 95, and 82.

Use the spread operator to combine both arrays into a new array called allScores.

Create another typed array called bonusPoints containing the numbers 5 and 10.

Use the spread operator to create a final array called finalScores that combines allScores with bonusPoints, but also includes the individual number 100 at the beginning and the number 90 at the end.

Print the finalScores array to the console.

Try it yourself

// TODO: Write your code here

console.log(finalScores);
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Introduction To TypeScript