CodeBlanks Logo Icon CodeBlanks

Array methods

Learn array methods like push, pop, and map.

Array methods

To add elements to an array use push, and to remove the last element use pop. The map method applies a function to each element and returns a new array. TypeScript checks these methods by their types.

let liste: number[] = [1, 2];
liste.push(3);   // [1, 2, 3]
liste.pop();     // [1, 2]

Details of push, pop and map

push appends an element to the end and returns the new length. pop removes the last element and returns it. map creates a new array, so the original array stays unchanged. Adding a wrong-typed element gives a compile error.

let isimler: string[] = ["Ali"];
isimler.push("Ayşe");
let ikili: number[] = [1, 2, 3].map(x => x * 2);
// [2, 4, 6]

Practice Double the numbers

Define a number[] array named sayilar with the values [1, 2, 3]. Use map to multiply each element by two and store it in a new array called ikili. Then print the ikili array.

Starter code

index.ts
// sayilar dizisini [1, 2, 3] olarak tanımla, map ile çiftle ve yazdır

Sample solution

index.ts
let sayilar: number[] = [1, 2, 3];
let ikili: number[] = sayilar.map(x => x * 2);
console.log(ikili);

Expected output

[ 2, 4, 6 ]

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does the `map` method do?

  • It removes an element from the array
  • It applies a function to each element and returns a new array Correct answer
  • It converts the array to a string
  • It mutates the array in place

Explanation: `map` applies a function to each element and returns a new array; the original array is untouched.

2 Add an element with push

Question
let meyveler: string[] = ["elma"];
meyveler.____;
Answer
let meyveler: string[] = ["elma"];
meyveler.push("armut");

Explanation: `push` adds a new element to the array; `pop` is for removal and `map` for transformation.

3 Method behaviors

Term Meaning
push Appends an element to the end
pop Removes and returns the last element
map Transforms each element and returns a new array
x => x * 2 A doubling function for map

All lessons in Beginner