Accessing & Modifying Elements


Accessing and Modifying Elements: Indexing (arr[0]), beyond bounds behavior

In JavaScript, you can directly access and change array elements using their zero-based index inside square brackets. If you try to access an element at an index that doesn't exist, JavaScript returns undefined. Interestingly, you can also assign a value to an out-of-bounds index, which will expand the array and fill any gaps with empty slots.


Example 1: Accessing the First Element

// Define an array of popular JavaScript frameworks
const frameworks = ["React", "Vue", "Angular"];

// Access the first element using index 0
const firstFramework = frameworks[0];

// Log the result to the console
console.log(firstFramework); // Output: "React"

Explanation: This code snippet demonstrates how to access the very first item in an array. Since arrays are zero-indexed, the element at the beginning is always at index 0.


Example 2: Accessing the Last Element

// An array of common programming languages
const languages = ["JavaScript", "Python", "Java", "C++"];

// Access the last element using the array's length property
const lastLanguage = languages[languages.length - 1];

// Display the last language
console.log(lastLanguage); // Output: "C++"

Explanation: To get the last element of an array, you can use its length property. Since the indexing starts at 0, the last element's index is always one less than the total number of elements.


Example 3: Modifying an Existing Element

// An array of browser names
let browsers = ["Chrome", "Firefox", "Safari"];

// Change the value of the element at index 1
browsers[1] = "Edge";

// Show the modified array
console.log(browsers); // Output: ["Chrome", "Edge", "Safari"]

Explanation: This example shows how to change an existing value within an array. By targeting an element's index, you can directly assign a new value to it, effectively overwriting the original.


Example 4: Accessing an Element Beyond Bounds

// An array of version control systems
const vcs = ["Git", "SVN", "Mercurial"];

// Attempt to access an element at an index that does not exist
const nonExistent = vcs[5];

// Log the result, which will be undefined
console.log(nonExistent); // Output: undefined

Explanation: When you try to access an array element at an index greater than or equal to the array's length, JavaScript doesn't throw an error. Instead, it gracefully returns the primitive value undefined.


Example 5: Adding an Element Beyond Bounds

// An array of package managers
let packageManagers = ["npm", "yarn"];

// Add a new element by assigning to an out-of-bounds index
packageManagers[3] = "pnpm";

// Notice the empty slot created at index 2
console.log(packageManagers); // Output: ["npm", "yarn", <1 empty item>, "pnpm"]
console.log(packageManagers.length); // Output: 4

Explanation: If you assign a value to an array index that is beyond its current size, JavaScript expands the array. Any indices between the previous last element and the new element are created as empty slots.


Example 6: Using an Expression as an Index

// An array of data types
const dataTypes = ["string", "number", "boolean", "object"];
let index = 1;

// Access an element using a variable expression as the index
const selectedType = dataTypes[index + 1];

// Log the accessed data type
console.log(selectedType); // Output: "boolean"

Explanation: You are not limited to using literal numbers as indices. Any expression that evaluates to a valid number can be used inside the square brackets to access an array element.


Example 7: Accessing Elements in a Multidimensional Array

// A 2D array representing a simple grid
const grid = [
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9]
];

// Access the element in the second row, third column
const centerElement = grid[1][2];

// Display the selected element
console.log(centerElement); // Output: 6

Explanation: For nested or multidimensional arrays, you can access elements by chaining square bracket notations. The first index selects the outer array's element, and the subsequent indices access elements within the nested arrays.