Flat Preloader Icon

Array In JS

Arrays in JavaScript are versatile data structures used to store collections of elements. They can hold elements of any data type, including numbers, strings, objects, functions, and even other arrays.

Definition:

  • An array in JavaScript is a special type of object used to store multiple values sequentially under a single variable name. Unlike other programming languages, JavaScript arrays are dynamic, meaning their size can change dynamically by adding or removing elements.

Declaration:

  • Arrays in JavaScript can be declared using either array literals or the Array() constructor:
  1. Array Literals:

				
					let arrayName = [element1, element2, ...];

				
			

2.Array Constructor:

				
					let arrayName = new Array(element1, element2, ...);

				
			

Characteristics:

  • Dynamic Size: JavaScript arrays can grow or shrink dynamically. You don’t need to specify the size when creating an array.

  • Ordered Collection: Arrays maintain the order of elements as they are inserted. You can access elements by their index, starting from 0 for the first element.

  • Mixed Data Types: Arrays can hold elements of any data type, and elements within the same array can be of different types.

Accessing Elements:

  • You can access elements in an array using square brackets [] with the index of the element:

				
					let array = [10, 20, 30];
console.log(array[0]); // Output: 10

				
			

Array Methods:

JavaScript arrays come with a variety of built-in methods to manipulate their elements. Some common array methods include:

  • push(): Adds one or more elements to the end of the array.
  • pop(): Removes the last element from the array.
  • shift(): Removes the first element from the array.
  • unshift(): Adds one or more elements to the beginning of the array.
  • splice(): Adds or removes elements from the array at a specified index.
  • slice(): Returns a shallow copy of a portion of an array into a new array object.
  • forEach(): Executes a provided function once for each array element.
  • forEach(): Executes a provided function once for each array element.
				
					let fruits = ['apple', 'banana', 'orange'];

// Add an element
fruits.push('grape');

// Remove the first element
fruits.shift();

// Access elements using loop
for (let i = 0; i < fruits.length; i++) {
    console.log(fruits[i]);
}