- JavaScript Basics
- JavaScript Tutorial
- JavaScript: where to write
- JavaScript: how to display
- JavaScript: keywords
- JavaScript: comments
- JavaScript: variables
- JavaScript: operators
- JavaScript: data types
- JavaScript Conditional Statements
- JavaScript: if-else
- JavaScript: switch
- JavaScript: for loop
- JavaScript: while loop
- JavaScript: do-while loop
- JavaScript: break and continue
- JavaScript Popup Boxes
- JavaScript: alert box
- JavaScript: confirm box
- JavaScript: prompt box
- JavaScript Popular Topics
- JavaScript: functions
- JavaScript: innerHTML
- JavaScript: getElementById()
- JavaScript: getElementsByClassName()
- JavaScript: getElementsByName()
- JavaScript: getElementsByTagName()
- JavaScript: querySelector()
- JavaScript: querySelectorAll()
- JavaScript: document.write()
- JavaScript: console.log()
- JavaScript: boolean
- JavaScript: events
- JavaScript: Math object
- JavaScript: Math.random()
- JavaScript: Number()
- JavaScript: parseInt()
- JavaScript: parseFloat()
- JavaScript Arrays
- JavaScript: array
- JavaScript: find length of array
- JavaScript: add element at beginning
- JavaScript: add element at end
- JavaScript: remove first element
- JavaScript: remove last element
- JavaScript: get first index
- JavaScript: get last index
- JavaScript: reverse an array
- JavaScript: sort an array
- JavaScript: concatenate arrays
- JavaScript: join()
- JavaScript: toString()
- JavaScript: from()
- JavaScript: check if value exists
- JavaScript: check if array
- JavaScript: slice an array
- JavaScript: splice()
- JavaScript: find()
- JavaScript: findIndex()
- JavaScript: entries()
- JavaScript: every()
- JavaScript: fill()
- JavaScript: filter()
- JavaScript: forEach()
- JavaScript: map()
- JavaScript Strings
- JavaScript: string
- JavaScript: length of string
- JavaScript: convert to lowercase
- JavaScript: convert to uppercase
- JavaScript: string concatenation
- JavaScript: search()
- JavaScript: indexOf()
- JavaScript: search() vs. indexOf()
- JavaScript: match()
- JavaScript: match() vs. search()
- JavaScript: replace()
- JavaScript: toString()
- JavaScript: String()
- JavaScript: includes()
- JavaScript: substr()
- JavaScript: slice string
- JavaScript: charAt()
- JavaScript: repeat()
- JavaScript: split()
- JavaScript: charCodeAt()
- JavaScript: fromCharCode()
- JavaScript: startsWith()
- JavaScript: endsWith()
- JavaScript: trim()
- JavaScript: lastIndexOf()
- JavaScript Date and Time
- JavaScript: date and time
- JavaScript: Date()
- JavaScript: getFullYear()
- JavaScript: getMonth()
- JavaScript: getDate()
- JavaScript: getDay()
- JavaScript: getHours()
- JavaScript: getMinutes()
- JavaScript: getSeconds()
- JavaScript: getMilliseconds()
- JavaScript: getTime()
- JavaScript: getUTCFullYear()
- JavaScript: getUTCMonth()
- JavaScript: getUTCDate()
- JavaScript: getUTCDay()
- JavaScript: getUTCHours()
- JavaScript: getUTCMinutes()
- JavaScript: getUTCSeconds()
- JavaScript: getUTCMilliseconds()
- JavaScript: toDateString()
- JavaScript: toLocaleDateString()
- JavaScript: toLocaleTimeString()
- JavaScript: toLocaleString()
- JavaScript: toUTCString()
- JavaScript: getTimezoneOffset()
- JavaScript: toISOString()
- JavaScript Regular Expression
- JavaScript: regular expression
- JavaScript: RegEx . (dot)
- JavaScript: RegEx \w and \W
- JavaScript: RegEx \d and \D
- JavaScript: RegEx \s and \S
- JavaScript: RegEx \b and \B
- JavaScript: RegEx \0
- JavaScript: RegEx \n
- JavaScript: RegEx \xxx
- JavaScript: RegEx \xdd
- JavaScript: RegEx quantifiers
- JavaScript: RegEx test()
- JavaScript: RegEx lastIndex
- JavaScript: RegEx source
- JavaScript Programs
- JavaScript Programs
Array in JavaScript (with Examples)
The word "array" means something like:
- arrangement
- line-up
- ordering
- collection
- group
And when we talk about an array in JavaScript, it indicates a collection or group of items stored in a single variable.
So, arrays in JavaScript are used when we need to store and use multiple items in a single variable. For example, let's suppose there are 120 students in a class where there are six subjects to cover. Therefore, to store marks for all six subjects, we either create separate variables for all subjects or use an array.
Create an array in JavaScript
There are two ways to create an array in JavaScript:
- Using array literals
- Using the new keyword (constructor).
Create an array in JavaScript using Array Literal
The most common method to create an array in JavaScript is by using array literals. Here is the syntax:
const arrayName = [item1, item2, item3, ..., itemN];
Notice: While declaring an array, I have used the constkeyword. This is because a variable declared using the const keyword can neither be updated nor re-declared. Also, a const variable must be initialized at the time of its declaration. So if, by mistake, we use the same variable to declare and/or define other values, then our browser will indicate that we are re-using that const variable, which at the end keeps the array constant.
Note: If you do not care or want to use the same variable again in the program, then you can follow the let keyword.
Here is an example of creating an array using array literals:
const marks = [89, 87, 93, 76, 69, 80];
What if there is no array supported by JavaScript? Then we have to create separate variables to store each value or mark of each subject, something similar to this:
const mark1 = 89; const mark2 = 87; const mark3 = 93; const mark4 = 76; const mark5 = 69; const mark6 = 80;
or something similar to:
const maths = 89; const physics = 87; const computer = 93; const chemistry = 76; const language = 69; const sports = 80;
For example:
<!DOCTYPE html> <html> <body> <p id="xyz"></p> <p><span id="a"></span>, <span id="b"></span>, <span id="c"></span>, <span id="d"></span>, <span id="e"></span>, <span id="f"></span></p> <script> const marks = [89, 87, 93, 76, 69, 80]; document.getElementById("xyz").innerHTML = marks; const maths = 89; const physics = 87; const computer = 93; const chemistry = 76; const language = 69; const sports = 80; document.getElementById("a").innerHTML = maths; document.getElementById("b").innerHTML = physics; document.getElementById("c").innerHTML = computer; document.getElementById("d").innerHTML = chemistry; document.getElementById("e").innerHTML = language; document.getElementById("f").innerHTML = sports; </script> </body> </html>
, , , , ,
See how difficult the job becomes when doing the same job but without using an array. So, arrays play a crucial role in storing multiple values using single variables. It also helps in accessing items and elements and outputting them in an easy and simple way. As you can see, while printing the marks of all 6 subjects without using an array, we have to remember and write a separate variable along with a separator (,).
Create an array in JavaScript using a new keyword
The same job (as done above) of creating an array in JavaScript can also be done in this way:
const arrayName = new Array(item1, item2, item3, ..., itemN);
For example:
const marks = new Array(89, 87, 93, 76, 69, 80);
Extra Information about an Array in JavaScript
While creating an array in JavaScript, spaces and line breaks are not important. Therefore, the same array can also be created in this way:
const marks = [ 89, 87, 93, 76, 69, 80 ];
We can also create a blank array and then define or initialize elements in it. For example:
const marks = []; marks[0] = 89; marks[1] = 87; marks[2] = 93; marks[3] = 76; marks[4] = 69; marks[5] = 80;
In the above JavaScript code snippet, 0, 1, 2, 3, 4, and 5 are indexes of an array that can be used to access array elements further.
Note: Since indexing always starts with 0, an element at index number [0] refers to the first value, whereas an element at index number [1] refers to the second value, and so on.
Access Array Elements in JavaScript
After understanding all the concepts above this paragraph, I don't think you still need to understand how array elements are accessed. Anyway, let me tell you, to access array elements, just use the array name along with the index numbers of the elements in this way:
arrayName[index]
For example, to access the third element, or element available at index number [2] of the array named marks, here is the syntax:
marks[2]
For example:
<!DOCTYPE html> <html> <body> <p id="myPara"></p> <script> const marks = [89, 87, 93, 76, 69, 80]; let thirdMark = marks[2]; document.getElementById("myPara").innerHTML = thirdMark; </script> </body> </html>
Change or update an array in JavaScript
We can also change or update an array further by changing or updating its element(s). For example:
<!DOCTYPE html> <html> <body> <p>Original Array: <b><span id="one"></span></b></p> <p>Updated Array: <b><span id="two"></span></b></p> <script> const marks = [89, 87, 93, 76, 69, 80]; document.getElementById("one").innerHTML = marks; marks[2] = 100; document.getElementById("two").innerHTML = marks; </script> </body> </html>
Original Array:
Updated Array:
The element at index [2] is updated in the above example.
Array in JavaScript Example
<!DOCTYPE html> <html> <body> <script> const marks = [89, 87, 93, 76, 69, 80]; for(let i=0; i<5; i++) { console.log("Marks obtained in Subject No.", i+1, " = ", marks[i]); } </script> </body> </html>
The image below displays the results of the aforementioned example:
Arrays are objects in JavaScript
Since arrays are treated as objects in JavaScript, an array in JavaScript can also be created in this way:
const marks = { maths: 89, physics: 87, computer: 93, chemistry: 76, language: 69, sports: 80 };
Notice the curly braces, or {}, instead of the square braces, or [].
And therefore, using names, we can access members. For example:
document.write(marks.maths);
will produce 89. Here is the complete example:
<!DOCTYPE html> <html> <body> <p>Marks obtained in Mathematics: <b><span id="math"></span></b></p> <script> const marks = { maths: 89, physics: 87, computer: 93, chemistry: 76, language: 69, sports: 80 }; document.getElementById("math").innerHTML = marks.maths; </script> </body> </html>
Marks obtained in Mathematics:
We can use multiple types of values as elements of an array in JavaScript
In JavaScript, it is not necessary to use the same type of value while defining elements for an array. We can use any kind of value, variable, or object to define an array. For example:
const myArray = [10, "CODESCRACKER", 12.32, true];
Characteristics of Arrays in JavaScript
Here is a list of some important characteristics of arrays in JavaScript:
- Arrays in JavaScript are resizable.
- Arrays in JavaScript can contain elements of different types.
- Arrays in JavaScript are not associative.
Important Methods and Properties of Arrays in JavaScript
- length: find the length of an array.
- unshift(): add an element to the beginning of an array.
- push(): add a new element at the end of an array.
- shift(): remove the first element from an array.
- pop(): remove the last element from an array.
- indexOf(): get the first index of a value in an array.
- lastIndexOf(): get the last index of an element in an array.
- reverse(): reverse an array.
- sort(): sort an array in ascending, descending, and alphabetical order.
- concat(): concatenate two or more arrays.
- join(): convert an array into a string.
- toString(): get a string from an array.
- from(): get an array from an iterable object.
- includes(): check if the specified value exists in an array.
- isArray(): check if an object is an array or not.
- slice(): slice an array.
- splice(): add and/or remove array elements.
- find(): find the first element that satisfies the given condition.
- findIndex(): get the index of the first element that meets the given condition.
- entries(): convert an array to an iterator object.
- every(): check if all values in an array are true.
- fill(): overwrites the specified array by filling the specified elements.
- filter(): filter an array based on a condition.
- forEach(): call a function for each item in an array.
- map(): map an array to create a new updated array.
Please note: A few methods, which are very rarely used in rare cases, are skipped.
« Previous Tutorial Next Tutorial »