Array Elements in JavaScript
The basic data structures in JavaScript for storing collections of values are arrays. Basically, they are lists of values. Any data type can be used for these values, or elements; in fact, an array can have numerous data types in one list. Store several variables in a single variable, such test scores, groceries, or a list of students, is frequently quite helpful.
Every element in an array has an index, which is a numerical location assigned to it. Arrays access those elements using these integers.
The Importance of Zero: Zero-Based Indexing
Understanding that JavaScript arrays are zero-indexed is essential when working with them. Accordingly, the array’s initial element’s index is always 0 rather than 1. The indices of an array will range from 0 to number of elements – 1 if it contains a specific number of constituents. It takes some getting accustomed to, but zero-based counting has a long history in technology and makes sense in some respects. You can think of the index as the number of items that should be skipped from the array’s beginning. As a result, index 0 lands on the first element after skipping zero items upfront.
For example, in an array like [“Toyota”, “Renault”, “Volkswagen”]:
- “Toyota” is at index 0.
- “Renault” is at index 1.
- “Volkswagen” is at index 2.
Accessing Elements
The square bracket ([]) operator is used to access an array element. Inside the braces, you enter the desired index number and a reference to the array on the left.
Here is an example showing how to access elements based on their index:
let cars = [“Toyota”, “Renault”, “Volkswagen”]; // An array of strings
// Accessing elements using their index
console.log(cars); // Accesses the first element, which is at index 0
// Output: Toyota
console.log(cars); // Accesses the second element, which is at index 1
// Output: Renault
console.log(cars); // Accesses the third element, which is at index 2
// Output: Volkswagen
A non-negative integer can be obtained from any expression that can be used as the index number.
Setting or Overwriting Elements
Setting or overwriting an element’s value at a given location uses the same syntax, which includes square brackets and the index number.
const arr = [1, 2, ‘c’, 4, 5]; // An array
// Overwriting the value at a specific index
arr[1] = 3; // Changes the value at index 2 from ‘c’ to 3
console.log(arr); // Output:
As a result, you can modify the value that is stored at a specific array index.
What About Indices That Don’t Exist?
Undefined will be returned by JavaScript if you attempt to access an index that is not present in the array.
let lengthsOfString = [“hello”.length, “world”.length, “example”.length, “test”.length]; // An example array
console.log(lengthsOfString); // Trying to access index 4 in an array with elements at 0, 1, 2, 3
// Output: undefined
Interestingly, JavaScript can generate an element and possibly expand the array if you try to assign a value to an index that doesn’t exist yet, such as negative indices or indices that are far longer than the current length.
let cars = [“Toyota”, “Renault”, “Volkswagen”]; // Starting array
cars = “Kia”; // Assigning a value to index 3, which didn’t exist (Comment is incorrect for this line)
cars[-1] = “Fiat”; // Assigning a value to a negative index
console.log(cars); // Output: Kia (Comment is correct for this line)
console.log(cars[-1]); // Output: Fiat (Comment might be incorrect for this line depending on runtime behavior)
console.log(cars); // Output might look like: [ ‘Toyota’, ‘Renault’, ‘Volkswagen’, ‘Kia’, ‘-1’: ‘Fiat’ ] (Comment is incorrect for this line)
To avoid errors like inadvertently overwriting data or skipping indices, the highlight that this is not the correct method for adding elements to an array. The Array methods section describes the proper ways to add elements.
Accessing the Last Element
Getting to an array’s last element is a frequent task. Because indices are zero-based and the greatest index is one less than the total number of elements, you may get the index of the final element by using the built-in length attribute. The array’s length property indicates how many elements it contains. The final element’s positional value will be length minus one as a result.
let names = [“Chantal”, “John”, “Maxime”, “Bobbi”, “Jair”]; // An array
console.log(names.length); // Output: 5
console.log(names[names.length – 1]); // Accesses the last element (index 4)
// Output: Jair
Arrays as Objects
You should be aware that arrays are a unique type of object in JavaScript. The names of integer properties are just array indices. The bracket notation with the index number is usually used to access the members of an array, however dot notation can be used to access named characteristics (such as length). In order to make accessing typical object attributes by name much slower than using numerical indexes, implementations frequently optimise arrays. A wide range of manipulation techniques are sent down from Array.prototype to arrays.
In conclusion, utilising the index of an array to access its elements is a basic JavaScript function. Utilising the square bracket notation and comprehending the zero-based indexing scheme, you can read or alter any element in an array according to its location.