Syncing account progress…

Back

Beginner · 10 min

Typed arrays

Keep collections consistent and handle an array that may be empty.

Describe the element type

number[] means an array of numbers. It does not mean an array with exactly one element. Methods such as map() infer the callback parameter from the array.

const prices: number[] = [3, 5];
console.log(prices.map(price => price * 2).join(", "));

Output

6, 10

Handle a missing element

An array can be empty. The playground enables noUncheckedIndexedAccess, so reading an array position may produce undefined. Choose a fallback or check the value.

const names: string[] = [];
const first = names[0] ?? "Nobody";
console.log(first);

Output

Nobody

Put it into practice

  1. Read the types and predict the output before running the examples.
  2. Complete the task, then check your understanding with the practice questions.

Try it yourself

Code runs on this device. When you are signed in, drafts sync to your account.

Keep an array numeric

Add the number 6 to "prices" and display their sum. Keep the number[] annotation.

Practice