Topic 41 of 87
Array Basics
Overview
Arrays are a special type of object used to store multiple values in a single variable. They are ordered, zero-indexed collections of data.
Imagine a shoe rack where every slot has a number. An array acts exactly like that rack, allowing you to group related items (like a list of users, shopping cart items, or recent search history) into a single, highly-manageable structure.
Syntax
Creating and Accessing
javascript
// Array Literal Syntax (Preferred)
const fruits = ["Apple", "Banana", "Mango"];
// Accessing elements via Index (Starts at 0)
console.log(fruits[0]); // "Apple"
console.log(fruits[2]); // "Mango"
// Modifying an element
fruits[1] = "Orange";
console.log(fruits); // ["Apple", "Orange", "Mango"]The Length Property
javascript
const colors = ["Red", "Blue", "Green"];
// Get the total number of items
console.log(colors.length); // 3
// Add to the very end dynamically
colors[colors.length] = "Yellow";Common Pitfalls
- JavaScript arrays are untyped, meaning you can store mixed data types in a single array:
[1, 'hello', true, {id: 1}]. This is terrible practice in modern development because it breaks predictability. Always try to keep arrays homogeneous (containing the same data type). - Because arrays are Objects in JS,
typeof [1, 2, 3]returns"object". To properly check if a variable is an array, you MUST useArray.isArray(myVar).
Interview Questions
Q:
How do you check if a variable is an array in JavaScript?
A:
You must use the built-in Array.isArray(variable) method. Using typeof will incorrectly return 'object' because arrays are technically just specialized objects under the hood.
Real-World Example
Storing the state of a user's shopping cart.
example
javascript
// An array of product ID strings
const shoppingCart = ["prd_101", "prd_892", "prd_444"];Check Your Knowledge
Test your understanding of Array Basics with these quick questions.