DEV Community

sai sanjana
sai sanjana

Posted on

Array basics

hi all,
Arrays are one of the most useful data structures in JavaScript. They allow you to store multiple values in a single variable instead of creating separate variables for each value. Arrays make it easier to organize, manage, and manipulate collections of data in your programs.

--What is an Array?
An array is a special variable that can hold more than one value at a time. The values stored in an array are called elements. Each element has a position called an index, and indexing starts from 0.

Example:

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

In this array, "Apple" is at index 0, "Banana" is at index 1, and "Mango" is at index 2.

--Creating Arrays:
There are different ways to create an array in JavaScript. The most common method is using square brackets.

let colors = ["Red", "Blue", "Green"];

You can also create an empty array and add values later.

let numbers = [];
numbers.push(10);
numbers.push(20);
Accessing Array Elements

You can access elements using their index number.

let fruits = ["Apple", "Banana", "Mango"];
console.log(fruits[1]);

Output:

Banana

-Remember that the first element always starts at index 0.

--Common Array Methods:
JavaScript provides several built-in methods to work with arrays.

-push():
Adds an element to the end of the array.

fruits.push("Orange");

-pop():
Removes the last element from the array.

fruits.pop();

-shift():
Removes the first element from the array.

fruits.shift();

-unshift():
Adds an element to the beginning of the array.

fruits.unshift("Grapes");

--Looping Through Arrays:
Loops are often used to access each element in an array.

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

for (let i = 0; i < fruits.length; i++) {
console.log(fruits[i]);
}

This loop prints all the elements in the array one by one.

--Advantages of Arrays:
Store multiple values in one variable.
Easy to access and update data.
Useful for lists, collections, and records.
Provide many built-in methods for data manipulation.

Therefore, arrays are an essential part of JavaScript programming. They help developers store and manage multiple values efficiently.

Top comments (0)