Arrays and Objects

Softinbit
5 min readJust now

An array in JavaScript is an ordered collection of elements, and it can store any type of data: numbers, strings, objects, or even other arrays (creating multi-dimensional arrays). Arrays are especially useful for storing ordered data and iterating over elements. In modern JavaScript, we also have new ways of handling arrays that enhance both functionality and readability.

Creating and Initializing Arrays

Here are the common methods of creating arrays:

// Array literal
let fruits = ["apple", "banana", "cherry"];

// Array constructor
let numbers = new Array(1, 2, 3);

// Array.of() method (introduced in ES6)
let mixedTypes = Array.of(10, 'twenty', { age: 30 });

// Array.from() method (converting array-like objects)
let stringArray = Array.from('hello'); // ["h", "e", "l", "l", "o"]

Array.from() allows us to create arrays from array-like or iterable objects, such as strings or NodeLists in the DOM. The method is particularly useful when you need to convert an object that behaves like an array into a true array.

Accessing and Modifying Elements

Accessing and modifying elements in arrays remain straightforward:

let firstFruit = fruits[0]; // Access first element
fruits[2] = "blueberry"; // Modify third element

--

--