DEV Community

Cover image for JavaScript Array
christopher
christopher

Posted on

JavaScript Array

Let’s Talk About Array in JavaScript

Array are Subject that allow us to store keyed collections. Just like naming a container where we have 1st, a 2nd, a 3rd element and so on. It can hold various data types, including numbers, strings, objects, and even other arrays. Arrays in JavaScript are zero-indexed i.e. the first element is accessed with an index 0, the second element with an index of 1, and so forth.

When working with arrays, it is easy to remove elements and add new elements using the arrays properties

Creating and Initializing Arrays

There are many ways to create arrays in JavaScript. The most common method is using the array literal syntax:

let fruits = [“apple”, “banana”, “orange”]

You can also initialize an array using the new array() constructor, though that is less common:

`let fruits = new Array("Apple", "Banana", "Cherry");`

Array Methods and Properties

JavaScript arrays come with a set of built-in methods and properties that make it easier to manipulate the data. here are some of the methods and Properties

  • push(): Adds one or more elements to the end of an array and returns the new length.
let numbers = [1, 2, 3];
numbers.push(4); 
console.log(numbers); // Outputs  Array[1,  2,  3,  4]
Enter fullscreen mode Exit fullscreen mode
  • pop(): Removes the last element from an array and returns that element.
  • shift(): Removes the first element from an array and returns that element
  • length: This property returns the number of elements in an array.
  • forEach(): This method executes a provided function once for each array element.
let fruits = ["apple", "banana", "cherry"];

fruits.forEach(function(item, index, array) {
  console.log(`${item}: ${index}`);
});

// Outputs  "apple: 0", "banana: 1", "cherry: 2"
Enter fullscreen mode Exit fullscreen mode

Spread Operator

The spread operator (...) in JavaScript allows an iterable (like an array or string) to be expanded in places where multiple elements or arguments are expected. It's incredibly versatile for array manipulations.

Best Practices for Using Arrays in JavaScript

  • Use const for declaring arrays that do not get re-assigned.

Using const for array declaration is a good practice. It prevents reassignment of the array identifier, ensuring the reference to the array remains constant. However, the contents of the array can still be modified.

Top comments (0)