JavaScript Arrays
# JavaScript Arrays
Imagine you are managing a classroom of 30 students. If you create a separate variable for every single student (let student1 = "John"; let student2 = "Alice";), your code will become a massive, unreadable mess.
This is where Arrays come in. An array is a special variable that can hold more than one value at a time.
1. Introduction
An array is an ordered list of values. You can store strings, numbers, booleans, and even functions or other arrays inside an array. Once you have your data grouped in an array, JavaScript gives you powerful tools (called "methods") to sort, filter, add, and remove items easily.
2. Learning Objectives
By the end of this chapter, you will be able to:
-
Create arrays using the array literal syntax
[].
- Access and modify specific items in an array using an index.
-
Use basic array methods:
push(),pop(),shift(), andunshift().
-
Use advanced array iteration methods:
map()andfilter().
- Build a working Todo List application using arrays.
3. Creating an Array
The easiest and most common way to create an array is using square brackets [], separating items with commas. This is called an Array Literal.
*Note: We usually declare arrays with const. The items inside the array can still be changed, but the array itself cannot be completely overwritten with a non-array value.*
4. Accessing Array Elements
You access an array element by referring to its Index Number. CRITICAL RULE: In JavaScript (and most programming languages), arrays are zero-indexed. The first item is at index 0, the second item is at index 1, and so on.
5. Array Length
Every array has a built-in property called length that tells you exactly how many items are inside it.
---
6. Real-world Examples & Code Snippets
Example 1: Creating and Accessing
Example 2: Changing an Array Element
You can overwrite a specific item by targeting its index.
Example 3: Mixed Data Types
An array can hold different types of data, though it's usually best to keep similar data together.
Example 4: push() - Add to End
The push() method adds a new item to the end of an array.
Example 5: pop() - Remove from End
The pop() method removes the last item from an array and returns it.
Example 6: unshift() - Add to Beginning
The unshift() method adds a new item to the beginning of an array.
Example 7: shift() - Remove from Beginning
The shift() method removes the first item from an array (shifting all other items down one index).
Example 8: Looping Through an Array
The classic way to go through every item in an array is using a for loop combined with the .length property.
Example 9: The map() Method (Advanced)
map() creates a brand new array by performing a function on every item in the original array. This is extremely powerful in modern JS (like React).
Example 10: The filter() Method (Advanced)
filter() creates a brand new array containing only the items that pass a specific test.
---
7. Common Mistakes for Beginners
-
1.
Forgetting Zero-Index: If an array has 3 items, trying to access
array[3]will returnundefined! The highest index is2(0, 1, 2).
-
2.
Writing over the length:
const arr = ["A"]; arr[5] = "B";This creates "empty holes" in your array for indices 1, 2, 3, and 4.
-
3.
Using
console.log(array)for users: The console formats arrays nicely. If you output an array directly to HTMLinnerHTML, it prints out as comma-separated text which is usually ugly. You need to loop through it to build HTML.
8. Best Practices
-
Always declare arrays with
const. It prevents you from accidentally overwriting the entire array with a string or number later.
-
Use
push()instead ofarray[array.length] = "new item"to add items.
-
Modern JavaScript developers prefer
map()andfilter()over writing rawforloops because it results in cleaner, more readable code.
9. Mini Project: Interactive Todo List
Let's build a simple Todo list using arrays to store our data, and a loop to update the HTML.
HTML:
todo.js:
10. Exercises
-
1.
Create an array called
movieswith 3 of your favorite movies. Console log the second movie in the array.
-
2.
Use the
push()method to add a 4th movie to your array.
-
3.
Write a
forloop that iterates through yourmoviesarray and console logs each one.
11. MCQs (Multiple Choice Questions)
Q1: What is the correct syntax for creating an array?
A) const arr = "A", "B", "C";
B) const arr = (A, B, C);
C) const arr = ["A", "B", "C"];
D) const arr = {"A", "B", "C"};
*Answer: C*
Q2: What is the index of the first item in an array? A) 0 B) 1 C) -1 D) It depends on the array length. *Answer: A*
Q3: Which method removes the LAST element from an array? A) shift() B) unshift() C) push() D) pop() *Answer: D*
12. Interview Questions
Q: What is the difference between push() and unshift()?
*A: Both methods add elements to an array. push() adds elements to the end of the array, while unshift() adds elements to the beginning of the array, shifting the existing elements to higher indexes.*
Q: Do map() and filter() modify the original array?
*A: No, map() and filter() are pure functions. They do not mutate the original array; instead, they return a brand new array containing the transformed or filtered items.*
13. FAQs
Q: Can I put arrays inside of arrays?
*A: Yes! This is called a Multidimensional Array. Example: const grid = [[1, 2], [3, 4]];. You access them like a grid: grid[0][1] returns 2.*
14. Summary
- Arrays store multiple values in a single variable.
-
Arrays are zero-indexed (
arr[0]).
-
Use
.lengthto find out how many items are in an array.
-
Methods:
push()(add end),pop()(remove end),unshift()(add start),shift()(remove start).
-
Use
forloops,map(), orfilter()to iterate over arrays.