Lesson 31 - Introduction to JavaScript Arrays
Arrays in JavaScript are used to store multiple values in a single variable. They are one of the most commonly used data structures. Let's take a moment to explore Arrays in JavaScript.
Explanation
- An array is a list-like object used to store multiple values.
- Elements in an array are indexed starting from
0
. - Arrays can hold elements of different types (numbers, strings, objects, etc.).
Example 1: Creating Arrays
let fruits = ['Apple', 'Banana', 'Mango'];
console.log(fruits); // ['Apple', 'Banana', 'Mango']
let mixedArray = [1, 'Hello', true, null];
console.log(mixedArray); // [1, 'Hello', true, null]
- Demonstrates how to create arrays with different data types.
Example 2: Accessing and Modifying Elements
let colors = ['Red', 'Green', 'Blue'];
console.log(colors[0]); // 'Red' (accessing the first element)
colors[1] = 'Yellow'; // Modifying the second element
console.log(colors); // ['Red', 'Yellow', 'Blue']
- Shows how to access and modify array elements using indexes.
Example 3: Array Length and Basic Methods
let numbers = [10, 20, 30, 40];
console.log("Length:", numbers.length); // 4
numbers.push(50); // Adds 50 to the end
console.log(numbers); // [10, 20, 30, 40, 50]
let last = numbers.pop(); // Removes the last element
console.log("Popped:", last); // 50
console.log(numbers); // [10, 20, 30, 40]
- Uses
length
,push()
, andpop()
methods.
Try Your Hand
Steps:
-
Create a File:
- Name it
lesson31-arrays.html
.
- Name it
-
Write the Code:
-
Copy the following code:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Lesson 31 - JavaScript Arrays</title> </head> <body> <h2>My Favorite Movies</h2> <ul id="movieList"></ul> <script> let movies = ['Inception', 'Interstellar', 'The Matrix', 'Parasite']; let list = document.getElementById("movieList"); movies.forEach(function(movie) { let li = document.createElement("li"); li.textContent = movie; list.appendChild(li); }); </script> </body> </html>
-
-
Save the File.
-
Open it in a Browser to See the List of Movies.
Experiment
- Create an array of your favorite books and display them as a list.
- Add a button that adds a new item to the list when clicked.
- Try removing an element from the array using
.splice()
.
Key Takeaways
- Arrays store multiple values in a single variable.
- Use square brackets
[]
to create arrays. - Access elements using index numbers starting from
0
. - Use
.push()
,.pop()
, and.length
for basic operations.