Working with Arrays: Creating, Accessing, and Modifying Elements

Introduction

Working with arrays in JavaScript involves creating arrays, accessing elements, and modifying them.

Creating Arrays

You can create arrays in JavaScript using either the array literal syntax or the Array constructor.

Using Array Literals

let fruits = [
    'apple',
    'banana',
    'cherry'
];

Using the Array Constructor

let numbers = new Array(1, 2, 3, 4, 5);

Accessing Elements

Array elements are accessed using zero-based indexing.

Accessing an Element

let firstFruit = fruits[0];      // 'apple'
let secondNumber = numbers[1];   // 2

Modifying Elements

You can modify array elements by assigning a new value to a specific index.

Modifying an Element

fruits[1] = 'blueberry'; // changes 'banana' to 'blueberry'
numbers[3] = 42; // changes the number at index 3 to 42

Complete Example

// Creating an array using the array literal syntax
let colors = ['red', 'green', 'blue'];

// Accessing elements
console.log(colors[0]); // Output: 'red'
console.log(colors[2]); // Output: 'blue'

// Modifying elements
colors[1] = 'yellow';
console.log(colors); // Output: ['red', 'yellow', 'blue']

// Adding elements to the end of an array
colors.push('purple');
console.log(colors); // Output: ['red', 'yellow', 'blue', 'purple']

// Iterating over an array
colors.forEach(function(color) {
    console.log(color);
});
// Output:
// 'red'
// 'yellow'
// 'blue'