When we're dealing with large amounts of data, we want to make sure we can organize and manage it properly.
In JavaScript, we use arrays to store several pieces of data in one place.
Array Declaration / Creation:
You start an array declaration with an opening square bracket, end it with a closing square bracket, and put a comma between each entry, like this:
let sandwich = ["peanut butter", "jelly", "bread"]
In this program we created an array consisting of 3 string items: "peanut butter", "jelly" and "bread".
Then, we stored that array in a variable sandwich
so we can later access it. For example, I can print the array:
// Creating the array:
let sandwich = ["peanut butter", "jelly", "bread"];
// Printing the array:
console.log(sandwich); // Output: ["peanut butter", "jelly", "bread"]
Items Data Types
Arrays can store any data types (strings, integers, booleans, etc.) and the items shouldn't necessary be of the same data type. For example:
let myArray = ["Hello world!", 32, False];
myArray
consits of one string
item, one number
item and one boolean
item.
We use arrays to better organize pieces of data which are part of the same family or share the same meaning, like the name of our friends or the items in a sandwich.
So most of the time we will have arrays where the items share the same data type.
Assignment
Follow the Coding Tutorial and let's play with some arrays.
Hint
Look at the examples above if you get stuck.
Arrays are a fundamental concept in JavaScript and many other programming languages. They allow us to store multiple values in a single variable, making it easier to manage and manipulate large sets of data. Arrays are particularly useful in scenarios where we need to perform operations on collections of data, such as sorting, filtering, and iterating over elements.
Before diving into more complex operations with arrays, it's essential to understand their basic structure and how to create them. An array is a list-like object that can hold multiple values, which can be of any data type. The values are stored in a sequence, and each value is accessed using an index, starting from 0.
Here's a simple example of an array:
let fruits = ["apple", "banana", "cherry"];
In this example, we have an array named fruits
that contains three string elements: "apple", "banana", and "cherry".
Let's explore some key concepts and techniques for working with arrays in JavaScript:
fruits[0]
will return "apple".fruits[1] = "blueberry"
will change "banana" to "blueberry".length
property returns the number of elements in an array. For example, fruits.length
will return 3.push()
and unshift()
. For example, fruits.push("date")
will add "date" to the end of the array.pop()
and shift()
. For example, fruits.pop()
will remove the last element, "cherry".Let's look at some examples to see how arrays can be used in different contexts:
// Example 1: Iterating over an array
let numbers = [1, 2, 3, 4, 5];
for (let i = 0; i < numbers.length; i++) {
console.log(numbers[i]);
}
// Example 2: Filtering an array
let evenNumbers = numbers.filter(function(num) {
return num % 2 === 0;
});
console.log(evenNumbers); // Output: [2, 4]
// Example 3: Mapping an array
let squares = numbers.map(function(num) {
return num * num;
});
console.log(squares); // Output: [1, 4, 9, 16, 25]
When working with arrays, it's important to be aware of common pitfalls and follow best practices:
length - 1
.push()
and splice()
. Consider using non-mutating methods like concat()
and slice()
when possible.map()
and filter()
can be more efficient than manual loops.Once you're comfortable with the basics, you can explore more advanced techniques for working with arrays:
let [a, b] = [1, 2]
assigns 1 to a
and 2 to b
....
) allows you to expand an array into individual elements. For example, let newArray = [...oldArray]
creates a shallow copy of oldArray
.reduce()
, find()
, and some()
. These methods can help you perform complex operations more concisely.Let's implement some of the concepts we've discussed with well-commented code snippets:
// Creating an array
let fruits = ["apple", "banana", "cherry"];
// Accessing elements
console.log(fruits[0]); // Output: apple
// Modifying elements
fruits[1] = "blueberry";
console.log(fruits); // Output: ["apple", "blueberry", "cherry"]
// Adding elements
fruits.push("date");
console.log(fruits); // Output: ["apple", "blueberry", "cherry", "date"]
// Removing elements
fruits.pop();
console.log(fruits); // Output: ["apple", "blueberry", "cherry"]
// Iterating over an array
for (let i = 0; i < fruits.length; i++) {
console.log(fruits[i]);
}
// Filtering an array
let numbers = [1, 2, 3, 4, 5];
let evenNumbers = numbers.filter(function(num) {
return num % 2 === 0;
});
console.log(evenNumbers); // Output: [2, 4]
// Mapping an array
let squares = numbers.map(function(num) {
return num * num;
});
console.log(squares); // Output: [1, 4, 9, 16, 25]
Debugging and testing are crucial parts of working with arrays. Here are some tips:
// Example test case
function sumArray(arr) {
return arr.reduce((sum, num) => sum + num, 0);
}
console.log(sumArray([1, 2, 3, 4, 5])); // Output: 15
console.log(sumArray([])); // Output: 0
When working with arrays, it's helpful to have a structured approach to problem-solving:
Arrays are a powerful and versatile tool in JavaScript, enabling you to work with collections of data efficiently. By mastering the basics and exploring advanced techniques, you can write more effective and maintainable code. Remember to practice regularly and apply these concepts to real-world scenarios to deepen your understanding.
For further reading and practice, check out these resources: