# JavaScript Arrays 101

## **<mark class="bg-yellow-200 dark:bg-yellow-500/30">What arrays are and why we need them</mark>**

In JavaScript, an **array** is **<mark class="bg-yellow-200 dark:bg-yellow-500/30">a specialized object used to store multiple values in a single variable</mark>**. Unlike standard variables that hold one value (like a single name), an array serves as an **ordered collection** of items, where each item is called an element and has a numeric position known as an **index.**

**Key Characteristics of JavaScript Arrays**

*   **Zero-Indexed**: The first element is at index `0`, the second at index `1`, and so on.
    
*   **Dynamic Size**: They can grow or shrink automatically as you add or remove elements.
    
*   **Heterogeneous**: A single array can store a mix of different data types, such as strings, numbers, objects, or even other arrays.
    
*   **Built-in Methods**: They come with powerful built-in functions like `push()`, `pop()`, `map()`, and `filter()` for easy data manipulation.
    

**Why We Need Arrays**

Arrays are essential for writing clean, efficient, and scalable code  
**Code Organization**: Without arrays, storing a list of 100 items would require 100 separate variables (e.g., `item1`, `item2`, etc.). An array allows you to group these into one variable, such as `items`.

*   **Efficient Data Processing**: Because arrays are ordered and indexed, you can easily use loops to perform the same action on every item (e.g., calculating a total or searching for a specific value).
    
*   **Fast Access**: Arrays provide direct access to any element if you know its index, which is highly efficient for data retrieval.
    
*   **Foundation for Complex Data**: Most modern web applications receive data from servers as lists (e.g., a list of users or products), which are naturally represented as arrays of objects.
    

## **<mark class="bg-yellow-200 dark:bg-yellow-500/30">How to create an array</mark>**

The most common and recommended way to create an array in JavaScript is by **<mark class="bg-yellow-200 dark:bg-yellow-500/30">using array literal notation with square brackets</mark>** `[]`.

**1\. Array Literal (Recommended)**

This method is simple, readable, and generally faster.

*   **Empty array:** `const arr = [];`
    
*   **With values:** `const fruits = ["Apple", "Banana", "Cherry"];`
    
*   **Mixed types:** JavaScript arrays can hold different data types at once, such as strings, numbers, and booleans.
    
    *   `const mixed = ["Hello", 42, true];`
        

**2\. Array Constructor**

You can also use the `new Array()` constructor, though it is less common.

*   **With values:** `const colors = new Array("Red", "Green", "Blue");`
    
*   **With length:** Passing a single number creates an array with that many **empty slots**.
    
    *   `const emptySlots = new Array(5); // Creates an array with length 5`
        

**3\. Modern Static Methods**

ES6 introduced powerful static methods for specific use cases:

*   [**Array.from()**](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from)**:** Creates an array from an array-like or iterable object (like a string or a Set).
    
    *   `const letters = Array.from("abc"); // ["a", "b", "c"]`
        
*   **Array.of():** Creates an array from any number of arguments, regardless of type or number.
    
    *   `const numbers = Array.of(7); // [7]` (Unlike `new Array(7)` which creates 7 empty slots)
        

**4\. Creating and Filling**

To create an array of a specific size filled with a default value:

*   **Using .fill():** `const filled = new Array(3).fill(0); // [0, 0, 0]`
    
*   **Range of numbers:** Use `Array.from()` with a mapping function.
    
    *   `const range = Array.from({ length: 5 }, (_, i) => i + 1); // [1, 2, 3, 4, 5]`
        

## **<mark class="bg-yellow-200 dark:bg-yellow-500/30">Accessing elements using index</mark>**

In JavaScript, accessing elements by index **<mark class="bg-yellow-200 dark:bg-yellow-500/30">primarily applies to arrays and strings</mark>**. You can use standard bracket notation or modern methods like `.at()`.

**1\. Basic Indexing with Square Brackets** `[]`

The most common way to access an element is by placing its index in square brackets immediately after the array name.

*   **Zero-Based:** JavaScript is zero-indexed, meaning the first element is at index `0` and the last is at `array.length - 1`.
    
*   **Syntax:** `const item = myArray[0];`
    
*   **Behavior:** If you provide an index that doesn't exist, it returns `undefined`.
    

**javascript**

```plaintext
const colors = ["Red", "Green", "Blue"];
console.log(colors[0]); // "Red"
console.log(colors[1]); // "Green"
```

**2\. Using the** `.at()` **Method**

The [**Array.prototype.at**](http://Array.prototype.at)[**()**](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/at) method is a modern alternative (ES2022) that supports **negative indexing.**

*   **Positive Indexes:** Behaves exactly like square brackets.
    
*   **Negative Indexes:** Allows you to count back from the end. For example, `-1` returns the last element, and `-2` returns the second to last.
    

**javascript**

```plaintext
const colors = ["Red", "Green", "Blue"];
console.log(colors.at(0));  // "Red"
console.log(colors.at(-1)); // "Blue" (last element)
```

**3\. Comparison of Common Methods**

| **Method \[**[**1**](https://stackoverflow.com/questions/70456996/using-array-atindex-instead-of-arrayindex-in-javascript)**,** [**2**](https://blog.ignacemaes.com/the-easy-way-to-access-the-last-javascript-array-element/)**,** [**3**](https://www.youtube.com/watch?v=7COSh2UGHrE)**,** [**4**](https://www.youtube.com/watch?v=dJxApBmJ0I4)**,** [**5**](https://www.w3schools.com/js/js_array_methods.asp)**\]** | **Can Read** | **Can Write** | **Negative Indexing** | **Browser Support** |
| --- | --- | --- | --- | --- |
| `[]` **Brackets** | Yes | Yes | No (returns `undefined`) | All |
| `.at()` | Yes | No | Yes | Modern (90%+) |

**4\. Finding an Index by Value**

If you have the value but need its index, use these methods:

*   [**indexOf()**](https://www.w3schools.com/jsref/jsref_indexof_array.asp): Returns the **first** index where a given element can be found.
    
*   [**findIndex()**](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex): Returns the index of the first element that satisfies a **testing function**.
    

**5\. Accessing Object Properties by Index**

JavaScript [**objects**](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Indexed_collections) are not indexed like arrays. To access them by a "position," you must first convert them into an array.

*   `Object.keys(obj)[i]`: Gets the name of the \\(i\\)-th key.
    
*   `Object.values(obj)[i]`: Gets the value of the \\(i\\)-th property.
    

## **<mark class="bg-yellow-200 dark:bg-yellow-500/30">Updating elements</mark>**

Updating elements” usually means **changing HTML content, styles, or attributes** on a webpage using JavaScript.

### **1\. Select the element first**

Before updating anything, you need to **target the element**:

```plaintext
const el = document.getElementById("myText");
```

Other ways:

```plaintext
document.querySelector(".className");
document.getElementsByTagName("p");
```

### **2\. Update text/content**

```plaintext
el.textContent = "Updated text!";
```

OR

```plaintext
el.innerHTML = "<b>Bold text</b>";
```

`textContent` → plain text  
  
`innerHTML` → allows HTML

### **3\. Update styles**

```plaintext
el.style.color = "blue";
el.style.fontSize = "20px";
```

### **4\. Update attributes**

```plaintext
const img = document.querySelector("img");
img.src = "new-image.jpg";
img.alt = "Updated image";
```

### **5\. Add / remove classes**

```plaintext
el.classList.add("active");
el.classList.remove("old");
el.classList.toggle("dark-mode");
```

### **6\. Update form values**

```plaintext
const input = document.querySelector("input");
input.value = "New value";
```

* * *

### **Example (real use)**

```plaintext
<p id="demo">Hello</p>
<button onclick="changeText()">Click me</button>
```

```plaintext
function changeText() {
  document.getElementById("demo").textContent = "Text changed!";
}
```

* * *

## Visual idea

![https://images.openai.com/static-rsc-4/7mYp563kcdh9CIt2qUR8tx5eTrSs2-yVMw2-fNQK4E1AH_RIitMDdijhRiCmZzwiQwO4IsuXr9jUdBQIIpsxPDq9lFMdTt2hzNg89ks1IoKuhqcEmLHYXey9CM0P-DevUAB7qX7Iw0ccLMNmuhON6HXrhTpsBPs6GcJPaMlYbFfvYu7JJdhYd5pztpACoOSX?purpose=fullsize](https://images.openai.com/static-rsc-4/_FrtHjyfnyCkX3VH-TdUZL4X_VJbIWBr1MIROeCMqd2aXTrDbcBjIy34FNM17c_SjQdOrJJPTMmweUWYLDnU9V5eCkY76rPMs6agBd4Kt6AuA1qAKdopEEaEkZaH986-hVJWy1N5nhY6ANyc-EUwJvVHdxKWsVwNB1zmM-aVSdQ?purpose=inline align="center")

![https://images.openai.com/static-rsc-4/sSh2Bg86fGVGVjHDSrnqLmKYPpbYGKKwi6z_xoc7eLh24t8E_8gMnU9h_d4rPDcaeG00uTBwGfA1M-ZKJqg3awfzdx_Elw1Me28MOGTVv_PbUEYgfqcyO04fMfTACQ0xZUPr98fw7f3n8jd8RuA5FjKq8jOgoNoeBzw85ZdijfzCkeS9cW2B6CvQMIW0B6hd?purpose=fullsize](https://images.openai.com/static-rsc-4/nQRFZKlK_6IVxAQsltxHuVeps_cOiwaI6plfU4-mwGTu-0o2J5HZq49ezYyF-f58wn4EQnzk-2XS_-2v8jdtVHTW4_2am4GXUNdkDXZMLHImeInKlRDd2EWwezzIrLAVjHFfOfFEq-EeVFv0a9u1HvcerduDO7RZI0HtQmot5YM?purpose=inline align="center")

![https://images.openai.com/static-rsc-4/RteZiPty9O-0eO4mzb0VN9-30EXkQaWWsB4zAOvJXrPzKIvzMVFeXyivIU9a6npz1BHrPhu9e9bSv3CLcVbmDJhXcp-ooaXt2zBsJ91hC-x23sCZ9iYYLHAIFmsGHuYwiB1kMkmJrj4qCihe5FVGRz4Yp1XLiwn9KtdMvdt81iZzjdnhGamci51Fi9AjoxRY?purpose=fullsize](https://images.openai.com/static-rsc-4/PLaZXhF432b7dSdokOEY3GYFw5aMVglpA4WjtAFPZ-nVqWE5bba4y0wUi8pF2HOAqZr4oN2GxHlz6X7RebJ6qeFzi8ql0Sg9eK9yFW0tav_YgUdH9ICDxTeP0vG6-w02Z4DvoBXQni5awxiwdtfWYKzXe-bw6ocq77xjD1F0G9Y?purpose=inline align="center")

* * *

![](https://cdn.hashnode.com/uploads/covers/696b8ad807aa331fd53e50e4/dad2e3fe-e85f-4cf9-a597-9c5cc6fa42b6.png align="center")

## **<mark class="bg-yellow-200 dark:bg-yellow-500/30">Array length property</mark>**

The `length` property in JavaScript **<mark class="bg-yellow-200 dark:bg-yellow-500/30">represents the number of elements in an array</mark>**. It is an unsigned, 32-bit integer that is always numerically greater than the highest index in the array.

**Key Characteristics**

*   **Zero-Based Indexing**: Because arrays are zero-indexed, the `length` is always one more than the last index.
    
*   **Automatic Updates**: JavaScript automatically updates this property whenever you add or remove elements (e.g., using `push()` or `pop()`).
    
*   **Writable Property**: Unlike in many other languages, you can manually set the `length` property to resize an array.
    

**Common Uses**

*   **Getting Array Size**: Accessing `array.length` returns the current count of elements.
    
*   **Truncating an Array**: Setting the `length` to a value smaller than the current one deletes elements beyond that new index.
    
*   **Clearing an Array**: You can quickly empty an array by setting `array.length = 0`.
    
*   **Accessing the Last Element**: Use `array[array.length - 1]` to retrieve the final item.
    
*   **Iterating**: Frequently used as the limit in `for` loops to process every element.
    

**Behavior with Sparse Arrays**

If an array is "sparse" (has empty slots), the `length` property reflects the highest index plus one, rather than the actual count of defined items. For example:

**javascript**

```plaintext
const sparseArray = [1];
sparseArray[5] = 10;
console.log(sparseArray.length); // Outputs: 6
```

**Constraints**

*   **Range**: The value must be a non-negative integer less than \\(2^{32}\\) (4,294,967,296).
    
*   **Errors**: Setting `length` to a negative number or an invalid type (like a string that isn't a number) will throw a `RangeError`.
    

## **<mark class="bg-yellow-200 dark:bg-yellow-500/30">Basic looping over arrays</mark>**

Looping lets you **go through each element** of an array and perform operations.

### Example array

```plaintext
const numbers = [10, 20, 30, 40];
```

### **🔹 1.** `for` **loop (classic)**

```plaintext
for (let i = 0; i < numbers.length; i++) {
  console.log(numbers[i]);
}
```

Full control (index, conditions)

### **🔹 2.** `for...of` **loop (clean & modern)**

```plaintext
for (let num of numbers) {
  console.log(num);
}
```

Best for simply accessing values

### **🔹 3.** `forEach()` **method**

```plaintext
numbers.forEach(function(num) {
  console.log(num);
});
```

OR arrow function:

```plaintext
numbers.forEach(num => console.log(num));
```

Very common in real projects

### **🔹 4.** `map()` **(returns new array)**

```plaintext
const doubled = numbers.map(num => num * 2);
console.log(doubled);
```

Used when transforming data

### **🔹 5.** `for...in` **(not recommended for arrays)**

```plaintext
for (let index in numbers) {
  console.log(numbers[index]);
}
```

Works, but mainly for objects

### **Assignment:**

### **Step 1: Create an array of 5 favorite movies**

```plaintext
let movies = ["Inception", "Interstellar", "Avatar", "Titanic", "Avengers"];
```

### **Step 2: Print first and last element**

```plaintext
console.log("First movie:", movies[0]);
console.log("Last movie:", movies[movies.length - 1]);
```

### **Step 3: Change one value and print updated array**

```plaintext
movies[2] = "Joker";  // Changing "Avatar" to "Joker"

console.log("Updated array:", movies);
```

### **Step 4: Loop through the array and print all elements**

### Using `for...of` (recommended)

```plaintext
for (let movie of movies) {
  console.log(movie);
}
```

Output (example)

```plaintext
First movie: Inception
Last movie: Avengers
Updated array: [ 'Inception', 'Interstellar', 'Joker', 'Titanic', 'Avengers' ]
Inception
Interstellar
Joker
Titanic
Avengers
```

![](https://cdn.hashnode.com/uploads/covers/696b8ad807aa331fd53e50e4/40702680-b6ba-4a38-8691-1562d7a67dfc.png align="center")
