Creating & Accessing Arrays

Arrays in JavaScript are ordered collections that can store multiple values in a single variable. They are especially useful for grouping related data.

Creating Arrays

There are two common ways to create an array:

  • Using square brackets []: Most common and recommended.
  • Using the Array constructor: Less commonly used but still valid.

📌 Deep Dive: Array Creation

JAVASCRIPT
// Using square brackets
const fruits = ['apple', 'banana', 'cherry'];

// Using Array constructor
const numbers = new Array(1, 2, 3);
Illustration of creating_accessing_arrays
Illustration of creating_accessing_arrays

💡 Array Literal Preferred

Using square brackets [] is clearer and less error-prone than the Array constructor.

Accessing Array Elements

Each item in an array has an index, starting at 0 for the first element.

  • Access elements using bracket notation: array[index].
  • If you access an index outside the array's range, you get undefined.

📌 Deep Dive: Accessing Elements

JAVASCRIPT
const colors = ['red', 'green', 'blue'];

console.log(colors[0]); // "red"
console.log(colors[2]); // "blue"
console.log(colors[3]); // undefined (no element at index 3)

⚠️ Remember: Zero-Based Indexing

Array indices always start at 0, not 1. Accessing array[1] gets the second element.

Summary Table: Creating vs Accessing Arrays

Creating & Accessing Arrays at a Glance
ActionExample
Create array (literal)const arr = [1, 2, 3];
Create array (constructor)const arr = new Array(1, 2, 3);
Access first elementarr[0]
Access last elementarr[arr.length - 1] (see length property)

💡 Tip: Accessing Last Element

Use array[array.length - 1] to get the last element, since length counts items starting at 1 but indexes start at 0.