Exploring JavaScript Arrays: A Step-by-Step Journey
A Day with JavaScript Arrays
Table of contents
- What is an Array ? ๐๏ธ๐๐ข
What is an Array ? ๐๏ธ๐๐ข
An array is also known as a list. In JavaScript, it is a data type that can store multiple types of values. You can add any number of items to an array, and each item is assigned an index, starting from zero. This means the first item has an index of zero. JavaScript offers many array methods, and the ten most important ones are explained below through a story :
Morning Routine and Preparation ๐ ๐๏ธ๐ฟ๐ชฅ๐ฅ๐ผ
He wakes up in the morning, lying flat on a neatly arranged bed with a pillow under his head.
The alarm โฐ on his phone ๐ฑ rings, making him to open his eyes. He sits up, moves to the edge of the bed, and puts on his slippers. Without wasting any time, he freshens up and heads straight to his workspace.
Setting Up the To-Do List โ
Sitting in his study room, he opens his laptop ๐ป and turns it on. Once it's on, he spins up his favourite IDE, VS Code, and creates a JavaScript file to write his to-do list for the day.
.js
extension.Creating an Empty Array [๐๐๐ฒ]
He initializes an empty array named To-Do List ๐.
let todoList = [];
// let myTodoList = new Array(); //Other way to make an empty array
1. Using .push()
to Add Tasks โ
To plan his day, he adds multiple tasks to his To-Do List using the push()
method.
// appending one item
todoList.push("Coding");
//appending multiple itmes
todoList.push("Reading", "Exercise", "Family Time", "Food Shopping", "Watching a Movie")
The .push()
method is used to add one or multiple items to the end of an array.
Changing Plans
As he is about to begin his work, a friend calls and suggests going out together for a few hours. Since this plan will take up time, he realizes that watching a movie wonโt be possible.
2. Using .pop()
to Remove an Item โ
To adjust his schedule, he removes the movie task from his to-do list.
let todoList = [
'Coding',
'Reading',
'Exercise',
'Family Time',
'Food Shopping',
'Watching a Movie'
]
todoList.pop();
console.log(todoList);
//output: [ 'Coding', 'Reading', 'Exercise', 'Family Time', 'Food Shopping' ]
The .pop()
method removes the last item from an array and returns it, allowing it to be stored in a variable. It does not take any arguments.
let arr = [1,2,3,4,5]
let deletedItem = arr.pop(); //.pop() method returns an item
console.log(deletedItem)
//output: 5
Reviewing the List
Before moving forward, he decides to review the entire list to ensure nothing is missing.
Unreal twist
for
loop would have definitely been a smarter choice instead of using the at()
method one by one. ๐ But since we are only learning about arrays, letโs add some unreal twists to keep the story fun!3. Using .at()
to View Items ๐
He checks each item one by one using the at()
method.
let arr = ['one', 'two','three','four','five'];
let itemOnIndex = arr.at(1); //it returns the item that is on index 1 i.e. 'two' for this example.
console.log(itemOnIndex)
//output: two
You can use the .at()
method to check which item is at a specific index. When using it, you must include round brackets ()
.
Hereโs another simple way to find a value using an index, similar but slightly different:
You can directly access an array item using bracket notation array[index]
. This method is more commonly used and works the same as .at(index)
in most cases.
let arr = ['one', 'two','three','four','five'];
let itemOnIndex = arr[1]; //it also returns the item that is on index 1 i.e. 'two' for this example.
console.log(itemOnIndex)
//output: two
.at()
method and bracket notation [ ]
) have a secret difference!Letโs understand this with an example:
let arr = [1,2,3,4,5]
console.log(arr[-1])
//output: undefined
console.log(arr.at(-1))
//output: 5
So when we try to access the last item using negative indexing with bracket notation []
, JavaScript returns undefined
because, behind the scenes, JavaScript works like an object in the language, so it interprets it as a property, not an index
let arrayType = []
//checking type of array
console.log(typeof arrayType)
//output: object
However, using the .at()
method, it returns the last item of the array.
Filtering the List After Reading
After reading a book for 30 minutes, he decides to remove it from his list since the task is completed. Therefore, it is no longer needed in the array.
4. Using .filter()
to Remove Completed Tasks ๐ฎ
let myTodoList = new Array ("Reading", "Exercise", "Family Time", "Food Shopping", "Watching a Movie")
let updatedTodoList = todoList.filter(item => item !== "Reading");
console.log(updatedTodoList)
//output: [ 'Exercise', 'Family Time', 'Food Shopping', 'Watching a Movie' ]
The filter()
method returns a new array with updated values, while the original array remains unchanged. This method takes a function as an argument, called a callback function, which determines whether each item passes the test defined by the developer.
For example, in our case:
The callback function checks if an item is not equal to "Reading". If any item is equal to "Reading", it will not be added to the updated array. Hence, the filter()
method filters out items based on the condition defined in the callback function, which is passed as an argument.
Changing Plans Again
Later, his friend calls again to cancel their meeting due to another commitment. Now, he has time to watch a movie again. ๐ฟ
As you know, he is a coder, so he loves watching movies about coders and those inspired by real programmers. To save time searching for movies later, he has already made a list of films he wants to watch.
5. Using .findIndex()
to Locate an Item ๐
He planned to watch The Pirates of Silicon Valley, but he doesnโt know its exact position in his watchlist (which, in reality, is quite longโlol). So, he uses the findIndex()
method to locate the index of this movie. Hence, he finds the index of the movie he wants to watch in his watchlist. ๐ฌ
let watchlist = ["Snowden", "The Pirates of Silicon Valley", "The Social Network", "The Great Hack", "The Social Dilemma", "Jobs", "Iron Man"];
let movieIndex = watchlist.findIndex(movie => movie === "The Pirates of Silicon Valley");
console.log(`Watching: ${watchlist[movieIndex]}`);
//output: Watching: The Pirates of Silicon Valley
The findIndex()
method in JavaScript also takes a callback function as an argument. It checks each item one at a time based on a given condition. In our example, if an item is equal to "The Pirates of Silicon Valley", it returns the index of that item.
-1
.let watchlist = ["Snowden", "The Pirates of Silicon Valley", "The Social Network", "The Great Hack", "The Social Dilemma", "Jobs", "Iron Man"];
let movieIndex = watchlist.findIndex(movie => movie === "Blackhat");
console.log(movieIndex);
//output: -1
Learning More About Arrays
After watching the movie, he feels motivated and energized to resume his coding session, where he learns about another useful array method.
6. Using .with()
to Replace an Item ๐
let codingArray = ['Learning Arrays', 'Watching a video tutorial', 'Article of today\'s learning']
let updatedTodo = codingArray.with(1, "Project Work"); // Replacing the second task
console.log(updatedTodo);
// output: [ 'Learning Arrays', 'Project Work', "Article of today's learning" ]
The .with()
method takes two required arguments. The first argument is the index, which specifies the position of the item to be replacedโlike in our example, index 1
refers to "Watching a video tutorial" in the original array. The second argument is the new value that will replace the existing one.
In this case, the .with()
method will replace the value at index 1
with "Project work".
It returns a new updated array, while the original array remains unchanged.
Checking for a Task
After finishing his coding session, he thinks about going out to buy groceries for tomorrowโs breakfast. Before heading out, he wonders if groceries are still on his list or if someone from his family has already bought them. So, he checks his list again.
7. Using .includes()
to Verify an Item ๐
let todoList = ['Coding', 'Reading', 'Exercise', 'Family Time', 'Food Shopping', 'Watching a Movie']
if (todoList.includes("Food Shopping")) {
console.log("Time to buy groceries!");
}
//output: Time to buy groceries!
The includes()
method checks whether a specified item is in the Array or not. It returns true
if the item exists and false
if it doesnโt.
.includes()
method strictly checks each item in the array, starting from index 0
by default. It compares items using strict equality (===
), meaning both the value and type must match.let number = [1,2,3,4,5]
/*The `.includes()` method checks each item in the array from the first item to the last.
It stops immediately if a match is found and returns `true`; otherwise,
it continues until the end and returns `false`. */
console.log(number.includes(3))
// 3 === 3 (this is how it will check, here 3 match it will return true.
//output: true;
The .includes()
method in arrays actually takes two arguments:
First argument (required): The item to search for.
Second argument (optional): The index from where the search should start. If provided, the search begins from that index.
let todoList = ['Coding', 'Reading', 'Exercise', 'Family Time', 'Food Shopping', 'Watching a Movie']
//here includes method will start searching item from index 1. (item: 'Reading' is on index 1)
console.log(todoList.includes("Food Shopping", 1))
//Output: true
If the second argument is not specified, the search starts from the first item (index 0
) by default.
Keeping Only the Pending Tasks
Since he has already completed some activities, he decides to keep only the remaining ones. He has finished the first five tasks from the list so far. Now, he knows that only the last few items are left to start.
Remembering what he learned from the MDN documentation about array methods, he decides to use the slice()
method to keep only the remaining tasks.
8. Using .slice()
to Keep Specific Tasks โ๏ธ
let todoList = ['Coding', 'Reading', 'Exercise', 'Food Shopping', 'Watching a Movie', 'Family Time']
let updatedList = todoList.slice(5); // Keeping only tasks that are not yet completed
console.log(updatedList)
//output [ 'Family Time' ]
The .slice()
method can take two optional arguments:
First argument (startIndex): Specifies the index where the extraction begins.
Second argument (endIndex): Specifies the index where the extraction stops (excluding this index).
let array_1 = [1,2,3,4,5,6,7,8,9,10]
let array_2 = array_1.slice(2,5)
console.log(array_2)
//output: [ 3, 4, 5 ]
As shown in the example above, the first argument is 2
and the second is 5
, meaning the slicing starts from index 2
and goes up to index 4
. The second argument is exclusive, so slicing stops one step before the given end index.
By default, the .slice()
method starts slicing from index 0
if no argument is provided. It returns a shallow copy of the entire original array, meaning it does not modify the original array but creates a new one with the selected elements.
Merging Lists
Suddenly, he realizes that he forgot to make a list of tasks he wants to do at night. He quickly creates a new list but then wonders, "Why keep two separate lists?"
Since he has already completed most of the tasks from his previous list, he decides to merge both lists into one. To do this, he uses the concat()
method to combine the new list with his existing one.
9. Using .concat()
to Combine Lists ๐
let todoList = ['family time']
let secondList = ['recording a youtube video', 'watching a youtube video', 'prepare for tomorrow'];
todoList = todoList.concat(secondList);
console.log(todoList);
//output: ['family time', 'recording a youtube video', 'watching a youtube video', 'prepare for tomorrow']
The .concat()
method is used to merge items into a single array. It can take multiple arguments, including independent values, arrays, or objects. The returned array contains all items in the order they were provided in the .concat()
method, without modifying the original arrays.
let arr = [1,2,3,4,5]
//concat() method can take multiple arguments.
let updatedArray = arr.concat('six', 7, [8,9,10], {'key':'value'})
console.log(arr) // Original Array
//output: [ 1, 2, 3, 4, 5 ]
console.log(updatedArray) // updated Array
//output: [ 1, 2, 3, 4, 5, 'six', 7, 8, 9, 10, { key: 'value' } ]
This method returns a new merged array, as shown in the example above. Hence, the original array remains unchanged.
Wrapping Up the Day
Finally, he has completed all his tasks. Now, he wants to summarize everything in a single sentence to reflect on his productive day and feel proud of himself. ๐ฏ
10. Using .join()
to Form a Sentence ๐
let todoList = ['Coding', 'Reading', 'Exercise', 'Family Time', 'Food Shopping', 'Watching a Movie', 'recording a youtube video', 'watching a youtube video', 'prepare for tomorrow']
console.log(todoList.join('\n'))
//output:
/*
Coding
Reading
Exercise
Family Time
Food Shopping
Watching a Movie
recording a youtube video
watching a youtube video
prepare for tomorrow
*/
The .join()
method always returns a string and does not modify the original array. It can take one optional argument (called a separator), which defines how the array elements are joined together.
If no separator is provided, it defaults to a comma (,
).
let nums = [1,2,3,4,5]
console.log(nums.join()) // no argument is given.
//output: 1,2,3,4,5 // default argument comma is automatically given by Javascript.
With all tasks successfully completed, he finally goes to sleep, ending a productive day with JavaScript arrays! ๐ด๐