In this section, we will learn what the array is and how to use it in JavaScript.
What is JavaScript Array?
Arrays are compound data types. That means an array variable can store multiple data all at the same time.
For example:
const arr = [1,2,3,4,5,6];
Here, the `arr` is an array variable that stored all the values ranged from 1 to 6.
Note: arrays are also of type objects. This means if we apply the `typeof` operator on a variable that holds an array, we will get “object” as a result.
Example:
console.log(typeof arr); //"object"
Initialize an Array in JavaScript
An Array in JavaScript can be created and initialized in two ways:
- Array Literal
- Array Constructor
Declaration of Array in JavaScript: Array Literal
Here’s the structure of a literal array:
variableName = [elementOne, elementTwo, elementThree, elementFour, element_n];
`variableName`: This is the name of the variable in which we want to store the array in it.
Note: arrays are stored in the memory and only their memory address will be stored in the target variable. This means if we assign the value of the `variableName` to another variable, only the memory address of that array will be passed to another variable. So essentially both of the variables have the access to the same array and if one variable changed the elements of that array, the other one will also see this change. (You can check the memory management section to learn more about how objects are stored in the memory)
`[]`: we use the pair of brackets `[]` to define and put elements in an array.
`elements`: inside an array we can put primitive values of type (Boolean, Number, BigInt, Symbol, String, Undefined, Null) and objects as well.
Note: unlike those statically typed languages like Java and C#, inside an array in JavaScript, we can put elements of multiple different types. For example, the first value can be of type Number but the second one of another type like Boolean, etc.
`,`: each of the elements in an array is separated from the other via a comma `,`.
Note: inside an array we can set another array, which is called multidimensional array. This is covered in the multidimensional array section.
Example: Create an Array Literal in JavaScript
Let’s see an example of an array:
const arr = [undefined,undefined,null,null,5,6, true, "John", 'Doe',false, 33.5];
In this array, the first 2 elements are of type `Undefined`, the next 2 elements are of type `Null` and the rest are Number, Boolean, String, Boolean, and Number, respectively. All of these elements are stored in one array and to access each of these elements, we use the `arr` identifier as you’ll soon see how.
So as you can see, inside an array we can put miscellaneous types of data.
Note: an identifier that is created via the `const` keyword can be used to store an array as well. Be aware that, after initialization, the target identifier cannot point to another array. But in the target array, we can change, add, or remove elements from it. Basically, the const keyword locks the target identifier itself and not the object that it’s pointing at.
Declaration of Array in JavaScript: Array Constructor
The way we created an array so far is called array literal. This is the usual way of creating arrays in JavaScript. But there is another way to create arrays as well, and that is via the `Array` constructor.
The `Array` is essentially a function that we can put the `new` keyword in front of it and create a new array object.
Array Constructor Syntax:
const objArr = new Array(); const objArr2 = new Array(1,2,3,4,true, false);
Inside the `Array` constructor, we can optionally assign elements that we want to have in our array. But this is optional and of course, during the course of the program, we can add or remove elements from an array.
Note: if we create an array via the `Array` constructor and only put one number than its argument, like the example below:
const objArr = new Array(100);
In a situation like this, the number is considered as the length of the array. So in this example, the execution engine will create an array that has the length of 100 elements and we can in later times fill all the elements of this array with any value that we want. Also, no-matter if we set the length of an array explicitly or not, the size is dynamic and will increase automatically if we put more elements than the current size of the target array.
Note: Also, when we set the size of an array explicitly, all the elements will be set to the value `undefined` by default.
Example: using Array Constructor to construct a new array
const array = [false, true, 2,3,"four","Five"]; for (const element of array){ console.log(element); }
Output:
false true 2 3 Four Five
Note: please check the for of statement section if you’re not familiar with this statement.
JavaScript Array Index
In Arrays, each element has a number associated with it and that number is known as the index-number.
This index number defines the position of the target element in the target array.
The first element in an array always has the index of 0 and the last element has the index number of (Array_Size – 1) which means if the target array’s size is 10 (contained 10 elements) then the last element is in the position 9. Of course this is because index numbers in arrays start from 0 and not 1.
After creating an array, we can put a pair of brackets on the right side of the name of that array and set an index number to access the target element.
Note: the index number in arrays starts from 0;
Let’s say we have a variable named `arr` with these values:
const arr = [1,2,3,45,"Omid", "Jack", "John"];
Now, to access the first element of this array, we use the index number 0 like this:
arr[0];
This will return the element that is stored as the first element of the array.
If we want to access the second element of this array, we use the index number `1`.
arr[1];
Example: using JavaScript array index to access elements of arrays
const arr = [undefined,undefined,null,null,5,6, true, "John", 'Doe',false, 33.5]; console.log(arr[0]); console.log(arr[5]); arr[0] = "Omid"; console.log(arr[0]);
Output:
Undefined 6 Omid
Here we have an array named `arr` with a few elements in that array.
Now take a look at these statements:
console.log(arr[0]); console.log(arr[5]); arr[0] = "Omid"; console.log(arr[0]);
In the first statement, we called the target array `arr` and put the pair of brackets `[]` on the right side of the array. Inside the brackets we set the index number in which we want to access. So, because the index number is 0, the execution engine checked the first element of the array and returned the value of that element.
In the next statement, we set the index number 5. So the execution engine checked that index and returned the value that was stored in that location.
In the next statement:
arr[0] = "Omid";
Here, the call to the index 0 of the array `arr` occurred on the left side of the assignment operator. This means we’re trying to assign a value to the index 0 of the array `arr`. In a situation like this, the engine will take the value on the right side of the assignment `=` operator and assign that value to the index that we defined for the target array.
So in the final statement:
console.log(arr[0]);
You can see that the value of the index 0, which was `undefined` is now changed to the value `Omid`.
Add to Array in JavaScript
In JavaScript arrays are very dynamic. This means after creating an array, we can easily add a new element to that array and increase its size.
To do that, set an index number for the target array beyond its size and add a new value to that index.
For example, if the target index has 10 elements already (which means the index number from 0 to 9 is already filled with values) then we can put the index number 10 and assign a new value to that position.
Example: adding an element to an array
const arr = [1,2,3,4,5,6,7,8,9,10]; arr[10] = 11;
Now the `arr` array has a new element in its last index as:
[1,2,3,4,5,6,7,8,9,10]
You should know that arrays are very dynamic!
Consider this array:
const arr = [1,2];
Here, the `arr` array has only two elements. So the length or the size of this array is 2.
First of all, we can get the length of this array via the `length` property.
Note: the `length` property and a couple of other useful properties as well as methods are the JavaScript built-ins for arrays. The details of these properties and methods are covered in Array Method section.
Example: getting the length of an array in JavaScript
const arr = [1,2]; console.log(arr.length);
Output:
2
Now, because arrays in JavaScript are super dynamic, we can add an element for this `arr` array at an index beyond the length of the array. For example, we can set an element in the index number 100!
Example: adding elements to Array in JavaScript
const arr = [1,2]; console.log(`The length of the array: ${arr.length}`); arr[100] = "Jack"; console.log(`The length of the array after assignment: ${arr.length}`);
Output:
The length of the array: 2 The length of the array after assignment: 101
As you can see, the length of the array at first is 2 because there are only 2 elements in the array.
After that, when we assigned a value at the index number 100, the size of the array changed to 101.
The result basically shows that when we add an element to an array that is outside of the length of that array, the engine will change the size of that array as well to fit the new index number.
For this reason, when we add an element in the index number 100, the engine changed the size to 101 to fit the index number 100 as well.
Note: What we’ve done in that last example is a bad practice. This is because we’ve added 100 elements and only put one actual value to the last index of that array. This will waste the memory space and also looping through all these elements just to get one value at the last index, will waste the CPU’s cycle.
There are a couple of useful methods and properties that we can use on each array. These methods and properties are covered in the Array method section.
JavaScript Empty Array
In order to create an empty array using Array-Literal, all we need to do is to assign an empty pair of brackets to a variable. After that, the variable will hold an empty array.
Also, if we want to use the Array Constructor, we can simply call this constructor with the new keyword but don’t pass any argument to it.
Example: creating an empty array in JavaScript
const array = []; const array2 = new Array(); console.log(`The size of the array is: ${array.length}`); console.log(`The size of the array is: ${array2.length}`);
Output:
The size of the array is: 0 The size of the array is: 0
JavaScript Array of Strings
Alright, now let’s create an array of string values and loop through them using the for of statement.
Example: creating array of strings in JavaScript
const strArray = ["Jack","John","Ellen","Omid","Ian","Elon"]; for (const element of strArray){ console.log(element); }
Output:
Jack John Ellen Omid Ian Elon
Array of Object in JavaScript
Alright, now let’s create an array of objects in JavaScript
Example: creating array of object in JavaScript
const obj = { name: "Omid", lastName: "Dehghan" } const obj2 = { name: "Jack", lastName: "Doe" } const objArray = [obj,obj2]; objArray[1].name = "John"; for (const element of objArray){ console.log(element.name); }
Output:
Omid John
Note that we’ve used the index number 1 to access the second object and then used the dot `.` operator to access `name` property of the second object and changed this value to `John`.
This statement tells us that when we pass objects as the elements of an array, only a reference (the memory address) of those objects will be set as the elements of the target array. So if we use an array’s element to change a property of an object, this change will be applied to the main object and not a copy object!
Array to Object in JavaScript: Object.assign() Method
We mentioned that each element in an array has its own index value. For example, the first element starts with the index 0, the second element has the index of 1 and so on.
Now using the assign() method from the Object constructor function we can convert an array into object where each index number of the array acts as the key (property) and the value in that index will be used as the value of the key in the new object.
Note: the assign() method is explained in greater details in later section.
Object assign() Method Syntax:
Object.assign(targetObject, source)
Example: converting an array to object in JavaScript
const array = ["Ellen","Elon","Omid"]; const obj = Object.assign({},array); console.log(obj);
Output:
{0: "Ellen", 1: "Elon", 2: "Omid"}
JavaScript Array Associative
Indexes for Arrays in JavaScript are of type Number. But there are other languages that support names as the indexes for elements in an array.
These types of arrays are called associative arrays. For example, the Map object in Java, the Dictionary object in Python, etc.
Notes:
- If you think about it, objects in JavaScript are some form of arrays! So if you need to store multiple values in one location but can’t use numbers as the method of accessing those values (like the way we use index numbers in arrays), then you can use objects instead!
- Also, there’s an especial type of object in JavaScript that is called Map which we can use to create Associative arrays. Please check the JavaScript Map section to learn more about this object.
JavaScript Arrays and instanceof Operator
All arrays in JavaScript are an instance of the Array object. We can see this by applying the `instanceof` operator on an array in JavaScript.
Example: using JavaScript instanceof operator on arrays
const array = ["Ellen","Elon","Omid"]; const res = array instanceof Array; console.log(res);
Output:
true
How to Return an Array in JavaScript?
An array could also be returned from a function. Returning an array from a function is pretty much the same as other values.
Basically, the array itself is stored in a part of the heap memory and its memory address is in the target variable that represents the array.
Now calling the return statement to return an array would basically return the memory address of that array and not a copy of it! So basically, a reference to the original array will be returned from a function.
Example: returning an array in JavaScript
function simpleArray(){ const array = ["Ellen","Elon","Omid"]; return array; } console.log(simpleArray());
Output:
["Ellen", "Elon", "Omid"]
Length of JavaScript Array
As mentioned before, we can use the length property to get the length (the number of elements) an array currently has.
Example: Array Size in JavaScript
const array = ["Ellen","Elon","Omid"]; console.log(`The size of the array is: ${array.length}`);
Output:
The size of the array is: 3
JavaScript Iterate Array
We can use loop statements like `for of` and `for` statements to loop through the elements of an array.
Please check the related sections if you’re not familiar with these statements.
JavaScript for loop Array
Using the `for` statement, we can use the length of an array and loop through its entire elements.
Also, using this loop, we can specifically define how many items of the target array to loop through in order to either get or change its values.
Example: JavaScript for loop array
const array = ["Ellen","Elon","Omid"]; for (let i = 0 ; i< array.length; i++){ console.log(array[i]); }
Output:
Ellen Elon Omid
JavaScript Multidimensional Array
Multidimensional array is basically an array that its elements are themselves arrays.
This is explained in greater details in the multidimensional array section.