JavaScript Array – A Complete Guide for Beginners!
Free Web development courses with real-time projects Start Now!!
Earlier in our previous tutorial, we read about JavaScript Event Types. Moving ahead, now we will learn about JavaScript Array. In this article, we will understand what are arrays, how to create and work with them. We will discuss various methods to access, add/remove or manipulate a JavaScript Array. Last but not the least we will also go through the different types of arrays provided by JavaScript. The tutorial also includes some of the properties and methods you can use in an array.
So without wasting any time, let’s start with our best tutorial on JavaScript Array.
What is JavaScript Array?
Before starting with this tutorial, I would recommend you to read our tutorial on JavaScript Objects first. Because, you cannot learn JavaScript Arrays until and unless you understand JavaScript Objects. Arrays are a very powerful tool in JavaScript. The definition of an array in Java goes something like this: “An array is a collection of homogeneous elements, stored in a contiguous memory location.”
In JavaScript, while the memory location is still contiguous, homogenous elements are no longer required. This is because, in Java, we have to pre-decide the type of array we want to use. JavaScript has no such obligation. It’s perfectly fine to define an array with the following values: “Neha”, “DataFlair Web Services”, 26, 3.5, true. This is the array we will create in this tutorial. Let me explain the values a bit. Neha is an employee, age 26, of the company DataFlair Web Services. She has 3.5 years of work experience under her belt and her status for still working is true.
But you need to be very careful when you use this functionality in your program. You must define the array like this only if your array makes sense. If it doesn’t, you’ll create a mess in your program that will be very difficult to resolve. Also, unlike C, JavaScript Arrays have no fixed size. Thus, we can allocate memory to a new array element anywhere in the program we wish.
Create an Array in JavaScript
Since an array is a list-like object, there are three methods to create an array as well. The difference is that we use square brackets [ ] for arrays instead of curly braces { }. Let’s see the different methods for array creation in a little more detail.
1. Array Literal Method
The syntax to create an array literal is as follows:
var arrayName = [val1, val2, val3, …, valN];
JavaScript code to create the array using the literal method is given below:
Code:
<html> <body> <script> //creating an array with literal method var array1 = ["Neha", "DataFlair Web Services", 26, 3.5, true]; //accessing the values of the array document.write("Employee: " + array1[0] + "</br>"); document.write("Company: " + array1[1] + "</br>"); document.write("Age: " + array1[2] + "</br>"); document.write("Work Experience: " + array1[3] + "</br>"); document.write("Still Working?: " + array1[4] + "</br>"); </script> </html>
Screenshot:
2. Array Instance Method
Similar to objects, we use the new keyword to create the instance of an array. The syntax of creating an array using this method is as follows:
var arrayName = new Array( );
To add new elements in an array, we use the bracket notation.
The code below produces the same output as above.
Code:
<html> <body> <script> var array2 = new Array(); //creating an instance of the array //adding values array2[0] = "Neha"; array2[1] = "DataFlair Web Services"; array2[2] = 26; array2[3] = 3.5; array2[4] = true; //accessing the values of the array document.write("Employee: " + array2[0] + "</br>"); document.write("Working for: " + array2[1] + "</br>"); document.write("Age: " + array2[2] + "</br>"); document.write("Work Experience: " + array2[3] + "</br>"); document.write("Still Working?: " + array2[4] + "</br>"); </script> </body> </html>
Screenshot:
3. Array Constructor Method
The syntax to create an array with the help of the constructor method is as follows:
var arrayName = new Array(val1, val2, val3, …, valN);
The code below will yield the same output as the above two methods.
Code:
<html> <body> <script> //creating an array with constructor method var array3 = new Array("Neha", "DataFlair Web Services", 26, 3.5, true); //accessing the values of the array document.write("Employee: " + array3[0] + "</br>"); document.write("Working for: " + array3[1] + "</br>"); document.write("Age: " + array3[2] + "</br>"); document.write("Work Experience: " + array3[3] + "</br>"); document.write("Still Working?: " + array3[4] + "</br>"); </script> </body> </html>
Screenshot:
4. To Copy an Array
We use the slice() method in JavaScript to create a copy of an array. We can either copy the whole array or a part of it. It’s our choice, all you need to do is specify the start and end positions of the array. The syntax of a slice() method is as follows:
var newArrayName = oldArray.slice(start, end)
If you pass an empty method to the compiler, i.e. slice(), it will copy the complete array to the new array. Add the following codes in the compiler to copy the entire array and part of it respectively.
var newArray = array1.slice()
var newArray = array1.slice(start, end)
Output:
Take a deep dive into our tutorial on JavaScript Variable
Associative Array in JavaScript
We created an array object in the above three examples to print the output. But you’re still wondering if there is another way to accomplish that task; something compact, aren’t you? Well, I’ve got just the thing you want for situations like this: Associative Arrays.
Associative Arrays are dynamic objects that redefine as per the user’s needs. These arrays comprise of key: value pairs where the key may be an integer or string and the value can be of any data type. When we assign values to keys in an array variable, the array transforms into an object, losing its properties and methods as Array.
The syntax of creating an associative array is like this:
var arrayName = {key1: val1, key2: val2, …, keyN: valN};
I can accomplish my task with associative arrays in the following manner:
Code:
<html> <body> <script> //creating an associative array var associativeArray = {employee: "Neha", workingFor:"DataFlair Web Services", age: 26, workExperience: 3.5, stillWorking:true}; //accessing the values of the array for (arrayValue in associativeArray){ document.write(arrayValue + ": " + associativeArray[arrayValue] + "</br>"); } </script> </body> </html>
Screenshot:
Output:
This was much more effective when working with pairs, don’t you think? But you use the array object when the key is an integer, and when you want access to the special methods and properties of Arrays.
Accessing JavaScript Array Elements
You can use the indexOf() method in JavaScript to find out the index of a given element in the array. You can also get the value at a specific index.
The code in the console shows an example of each.
Add Element in JavaScript Array
Let’s say I want to add a characteristic of Neha in the above array, nationality: Indian. Use any of the three approaches explained above and add the code in the console.
1. At the end of an array
We use the array’s built-in method push() to add an element at the end of the list.
Code:
array1.push()
Output:
2. To the front of an array
We use the array’s built-in method unshift() to add an element at the front of the list.
Code:
array1.unshift()
Output:
We can insert an element in the middle of the array with the help of an array function splice(). This approach is described under array methods.
You must also explore JavaScript Functions that will help you further in learning JavaScript easily
Remove Element from JavaScript Array
I feel that I don’t really want Neha’s nationality in my records. I will remove it from the array element with the help of simple JavaScript code. Don’t forget, we’re using the console to test our code.
1. From the end of an array
We use the array’s built-in method pop() to remove an element from the end of the list.
Code:
array1.pop()
Output:
2. From the front of an array
We use the array’s built-in method shift() to remove an element from the front of the list.
Code:
array1.shift()
Output:
You can remove an element at any index position with the help of splice() method, explained below.
The Length Property
This JavaScript property returns the total number of elements present in an array. These update automatically as we modify the array. It doesn’t actually count the values of the array, but the largest numeric index plus 1. This is the reason we cannot access this property with an associative array. The length of an empty array is 0.
An interesting fact to know about the length property is that it’s writable. You can modify it manually; it shows no difference if you increase the length of the array. But, if you decrease the length of the array, it truncates the array i.e. it removes all the values, which aren’t covered in that limit.
The code to find the length of the array is as follows:
array1.length
Output:
The splice() method
You can add/ remove an array element from any position you want with the help of this JavaScript method. The syntax of a splice() method looks like this:
array.splice( start, deleteCount [, … items ] )
Insert the element in the array at position 2, without removing 0 elements from the array, with the help of the code:
array1.splice(2, 0, “Indian”)
Delete 1 item from the array at position 2 with the help of the following code:
array1.splice(2, 1)
Output:
Summary
Here we conclude our tutorial on JavaScript Array. There are many more methods and properties associated with arrays than we covered, you can test them all when you work with the browser console. All you need to do is create an array and put a dot operator after it. The console will list all the methods associated with that array object, you are free to use any of them whenever needed. But focus on the ones we covered in the tutorial and you’ll learn the other properties and methods as you practice more. Try all the programs mentioned above and experiment with them. For now, you must go through our next tutorial on JavaScript Data Structures.
Hope the article was fruitful for you. Still, if you have any queries feel free to share with us through the comment section below.
If you are Happy with DataFlair, do not forget to make us happy with your positive feedback on Google