본문으로 건너뛰기

Array Methods - length, pop, push, shift, unshift

Array Methods - length, pop, push, shift, unshift

Let's look at some important array methods that are frequently used.


1. length

The length property tells you how many items are in an array.

Example:

let fruits = ['apple', 'banana', 'cherry'];
console.log(fruits.length); // Outputs 3.

Here, the box contains three fruits, so it outputs the number 3.


2. pop

The pop method removes the last item from an array and returns that item. It's like taking the top item out of a box.

Example:

let fruits = ['apple', 'banana', 'cherry'];
let lastFruit = fruits.pop();
console.log(lastFruit); // Outputs "cherry".
console.log(fruits); // Outputs ["apple", "banana"].

3. push

The push method adds a new item to the end of an array. It's like stacking a new item on top of the box.

Example:

let fruits = ['apple', 'banana'];
fruits.push('cherry');
console.log(fruits); // Outputs ["apple", "banana", "cherry"].

4. shift

The shift method removes the first item from an array and returns that item. It's like taking the bottom item out of a box.

Example:

let fruits = ['apple', 'banana', 'cherry'];
let firstFruit = fruits.shift();
console.log(firstFruit); // Outputs "apple".
console.log(fruits); // Outputs ["banana", "cherry"].

5. unshift

The unshift method adds a new item to the beginning of an array. It's like putting a new item at the bottom of the box.

Example:

let fruits = ['banana', 'cherry'];
fruits.unshift('apple');
console.log(fruits); // Outputs ["apple", "banana", "cherry"].