Loading...

Arrays in JavaScript: Complete Guide With Examples [2022]

Arrays in JavaScript: Complete Guide With Examples [2022]

In the previous blog posts, you have seen how to store the value of one individual, Jason Bourne, in a JavaScript Object type. What if you had a class of 20 students? What would you do then? You have to store their name and age.

Would you create a separate variable for each student and refer to them by their variable name? Well, you can do that, but what if two students have the same name? Or what if, the name and hence the variable name becomes difficult? (Like Elon’s son: X Æ A-Xii)

You can see that as the number of individuals grows, it is going to be a hassle.

JavaScript provides a data structure to solve just this problem: Arrays

What are Arrays?

Arrays are data structures that can store multiple values at once.

stringArray = ["I", "love", "codedamn"]
Code language: JavaScript (javascript)

For instance, the stringArray above stores three string values at once!

But then what is a data structure?

It is a very specific format in which the computer stores data in its memory. Arrays, as a data structure, help you store many values in them. These values can be of the same data type, like all strings in the stringArray, or of different types, like:

mixedArr = ["I", "love", "codedamn", 3000]
Code language: JavaScript (javascript)

It is however good practice to store similar data types in an array to maintain predictability of the information it contains.

An array in itself is also an Object data type in JavaScript.

Data Type of Array
Data Type of Array

How to Create an Array?

let strArray = ["I", "love", "codedamn"]
Code language: JavaScript (javascript)

That is it. That is how you create an array. You define the variable type, const or let, followed by a variable name. You assign (“=”) the variable whatever values you want inside square brackets([]). The values are separated by a comma.

Want to try it out? Head over to codedamn playgrounds. For the code in this blog, use this playground directly.

The square brackets method of defining an array is referred to as using array literals. There is another way to do essentially the same thing using the new keyword. But we will discuss it later when we do functions.

Try storing the following details in an array:

NameAge
Jason22
Aaron23

Hints:

  • Represent each row as an Object
  • Create a variable students
  • Write each Object inside square brackets, separated by commas
  • Assign the values to students

You should end up with something like:

Objects in Arrays
Objects in Arrays

Can you take a guess on how to print this array onto the console? It is as easy as doing:

console.log(students)
Code language: JavaScript (javascript)
Printing an Array
Printing an Array

Check the output carefully. It shows:

  • [Object, Object]: Indicating that the values stored inside are of the Object data type
  • 0: Object: {name: "Jason", age: 22}: The data inside the curly braces is familiar. But what are these 0 and 1 values? You have not specified them anywhere.

Accessing Elements in an Array

What if I ask you to print the name Jason from the array onto the console? You are not allowed to do:

console.log("Jason")
Code language: JavaScript (javascript)

Because the value is not being accessed from the array!

The 0 and 1 you saw in the previous section will help you do this. They are called the indices (singular, index) of the data, in this case, Objects, inside the array.

In simple words, they denote the position of anything inside the array. The data for Aaron

Indexing
Indexing

is stored at position 1 in the array.

And in JavaScript or any other programming language, the first position starts from 0. It is called zero-based indexing.

So how do you print “Jason” then?

Indexing
Indexing

Use the variable name students. Since Jason is stored at position 0, inside square brackets, use 0. This is what is done in line 6. The general syntax is:

varName[positionIndex]
Code language: JavaScript (javascript)

We have stored the object in the variable obj1. Now you can access any attribute of the object with the dot notation.

Try printing Aaron’s age on the console.

Aaron's age
Aaron’s Age

This approach to accessing elements in an array is called indexing.

Add an Element to the Array

What if you get a new student Barry and you want to add him to the list students.

{name: "Barry", age: 21}
Code language: JavaScript (javascript)

You can use a method of the Array Object to add a new value to an existing array.

A method is simply an action, like adding an element or deleting an element in an array. You will delve deeper into creating your own actions or methods when we discuss functions.

In this case, to add an element to the array, we will use the push() method.

push method
push method

In line 7: we call the push on students and pass the Object for Barry with his name and age.

In the output,

{name: "Barry", age: 21}
Code language: JavaScript (javascript)

has been added at position 2 after Aaron.

Therefore, push adds a new element to the end of the array.

What would you do to add

{name: "Claire", age: 22}
Code language: JavaScript (javascript)

to the beginning of the array?

You can use the unshift method!

unshift method
unshift method

Claire was added to position 0, and the rest of the Objects were shifted by 1 to the next position.

Updating an Element

Updating an element is as easy as accessing the object using the index and assigning it a new value by using the “=” operator.

Suppose you want to change “Claire” to “Hermione”. Then you can do the following:

Updating an Element
Updating an Element

Total Elements in an Array

Finding the length of the array is one of the most common operations that you will perform while writing the code. And so it has its own property length!

Array length
Array length

Since we had added 4 people: Hermione, Jason, Aaron, and Claire, in the array, we get the output of 4.

If you see the code carefully, you will realize that length is missing the round brackets () we have previously seen. That’s because it is not a method but a property. JavaScript internally stores and updates this value. And you can access it without the brackets. It never takes an input, but always gives an output.

Conclusion

The blog introduced you to arrays in JavaScript and some of the most commonly used methods related to them. I’d recommend you glance through all the methods on the MDN documentation.

A word of advice would be to try and not mug these methods up, but rather look them up in the documentation whenever you want to perform a specific operation.

I’ll leave you with a question,

What if you had an array of 20 people with their names and age, and wanted to check if they were eligible to drive or not?

One approach would be indexing each element and checking the age, but then you would be repeating the same logic 20 different times. There has to be a better way! That will be the topic of our next blog.

Till then practice, practice, and practice on codedamn playgrounds!

Sharing is caring

Did you like what Rishabh Mittal wrote? Thank them for their work by sharing it on social media.

0/10000

No comments so far