DEV Community

Cover image for JavaScript Arrays for Beginners 🚀
Narasimma Radhakrishnan
Narasimma Radhakrishnan

Posted on

JavaScript Arrays for Beginners 🚀

When I started learning JavaScript, arrays were one of the first concepts I learned. Arrays are very useful when we need to store multiple values in a single variable.

What is an Array?

An array is a collection of multiple values.

let fruits = ["Apple", "Banana", "Mango"];

console.log(fruits);
Enter fullscreen mode Exit fullscreen mode

Output:

["Apple", "Banana", "Mango"]

Instead of creating three different variables, we can store everything inside one array.

Accessing Array Elements

Array indexing starts from 0.

let fruits = ["Apple", "Banana", "Mango"];

console.log(fruits[0]);
console.log(fruits[1]);
console.log(fruits[2]);
Enter fullscreen mode Exit fullscreen mode

Output:

Apple
Banana
Mango

Remember:

First element → index 0
Second element → index 1

Adding Elements
push()

Adds an element to the end.

fruits.push("Orange");

console.log(fruits);
unshift()
Enter fullscreen mode Exit fullscreen mode

Adds an element to the beginning.

fruits.unshift("Grapes");

console.log(fruits);
Removing Elements
pop()

Removes the last element.

fruits.pop();
shift()

Removes the first element.

fruits.shift();
Finding the Array Length

Use .length to find how many elements are inside the array.

let numbers = [10, 20, 30, 40];

console.log(numbers.length);
Enter fullscreen mode Exit fullscreen mode

Output:

4
Looping Through an Array

We can use a for loop to access every element.

let numbers = [10, 20, 30, 40];

for (let i = 0; i < numbers.length; i++) {
  console.log(numbers[i]);
}
Enter fullscreen mode Exit fullscreen mode

Output:

10
20
30
40

Top comments (0)