- JavaScript Basics
- JS Home
- JS Syntax
- JS Placements
- JS Output
- JS Statements
- JS Keywords
- JS Comments
- JS Variables
- JS var
- JS let
- JS const
- JS var Vs let Vs const
- JS Operators
- JS Arithmetic Operators
- JS Assignment Operators
- JS Comparison Operators
- JS Logical Operators
- JS Bitwise Operators
- JS Ternary Operator
- JS Operator Precedence
- JS Data Types
- JS typeof
- JS Conditional Statements
- JS Conditional Statement
- JS if Statement
- JS if...else Statement
- JS switch Statement
- JS Loops
- JS for Loop
- JS while Loop
- JS do...while Loop
- JS break Statement
- JS continue Statement
- JS break Vs. continue
- JavaScript Popup Boxes
- JS Dialog Box
- JS alert Box
- JS confirm Box
- JS prompt Box
- JavaScript Functions
- JS Functions
- JS setTimeout() Method
- JS setInterval() Method
- JavaScript Events
- JS Events
- JS onclick Event
- JS onload Event
- JS Mouse Events
- JS onreset Event
- JS onsubmit Event
- JavaScript Arrays
- JS Array
- JS Find Length of Array
- JS Add Elements at Beginning
- JS Add Element at End
- JS Remove First Element
- JS Remove Last Element
- JS Get First Index
- JS Get Last Index
- JS Reverse an Array
- JS Sort an Array
- JS Concatenate Arrays
- JS join()
- JS toString()
- JS from()
- JS Check if Value Exists
- JS Check if Array
- JS Slice an Array
- JS splice()
- JS find()
- JS findIndex()
- JS entries()
- JS every()
- JS fill()
- JS filter()
- JS forEach()
- JS map()
- JavaScript Strings
- JS String
- JS Length of String
- JS Convert to Lowercase
- JS Convert to Uppercase
- JS String Concatenation
- JS search()
- JS indexOf()
- JS search() Vs. indexOf()
- JS match()
- JS match() Vs. search()
- JS replace()
- JS toString()
- JS String()
- JS includes()
- JS substr()
- JS Slice String
- JS charAt()
- JS repeat()
- JS split()
- JS charCodeAt()
- JS fromCharCode()
- JS startsWith()
- JS endsWith()
- JS trim()
- JS lastIndexOf()
- JavaScript Objects
- JS Objects
- JS Boolean Object
- JavaScript Math/Number
- JS Math Object
- JS Math.abs()
- JS Math.max()
- JS Math.min()
- JS Math.pow()
- JS Math.sqrt()
- JS Math.cbrt()
- JS Math.round()
- JS Math.ceil()
- JS Math.floor()
- JS Math.trunc
- JS toFixed()
- JS toPrecision()
- JS Math.random()
- JS Math.sign()
- JS Number.isInteger()
- JS NaN
- JS Number()
- JS parseInt()
- JS parseFloat()
- JavaScript Date and Time
- JS Date and Time
- JS Date()
- JS getFullYear()
- JS getMonth()
- JS getDate()
- JS getDay()
- JS getHours()
- JS getMinutes()
- JS getSeconds()
- JS getMilliseconds()
- JS getTime()
- JS getUTCFullYear()
- JS getUTCMonth()
- JS getUTCDate()
- JS getUTCDay()
- JS getUTCHours()
- JS getUTCMinutes()
- JS getUTCSeconds()
- JS getUTCMilliseconds()
- JS toDateString()
- JS toLocaleDateString()
- JS toLocaleTimeString()
- JS toLocaleString()
- JS toUTCString()
- JS getTimezoneOffset()
- JS toISOString()
- JavaScript Browser Objects
- JS Browser Objects
- JS Window Object
- JS Navigator Object
- JS History Object
- JS Screen Object
- JS Location Object
- JavaScript Document Object
- JS Document Object Collection
- JS Document Object Properties
- JS Document Object Methods
- JS Document Object with Forms
- JavaScript DOM
- JS DOM
- JS DOM Nodes
- JS DOM Levels
- JS DOM Interfaces
- JavaScript Cookies
- JS Cookies
- JS Create/Delete Cookies
- JavaScript Regular Expression
- JS Regular Expression
- JS RegEx .
- JS RegEx \w and \W
- JS RegEx \d and \D
- JS RegEx \s and \S
- JS RegEx \b and \B
- JS RegEx \0
- JS RegEx \n
- JS RegEx \xxx
- JS RegEx \xdd
- JS RegEx Quantifiers
- JS RegEx test()
- JS RegEx lastIndex
- JS RegEx source
- JavaScript Advance
- JS Page Redirection
- JS Form Validation
- JS Validations
- JS Error Handling
- JS Exception Handling
- JS try-catch throw finally
- JS onerror Event
- JS Multimedia
- JS Animation
- JS Image Map
- JS Debugging
- JS Browser Detection
- JS Security
- JavaScript Misc
- JS innerHTML
- JS getElementById()
- JS getElementsByClassName()
- JS getElementsByName()
- JS getElementsByTagName()
- JS querySelector()
- JS querySelectorAll()
- JS document.write()
- JS console.log()
- JS instanceof
- 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 array in JavaScript, then it indicates a collection or group of items stored in a single variable.
So, array in JavaScript is used when we need to store and use multiple items through a single variable. For example, let's suppose there are 120 students in a class where there are 6 subjects to cover for each. Therefore, to store marks of all 6 subjects, either we 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 literal
- Using new keyword (Constructor)
Create an Array in JavaScript using Array Literal
Most used 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 const keyword. This is because, a variable declared using a const keyword can neither be updated nor be 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 for other values, then our browser will indicate that we are re-using that const variable, which at the end keep the array constant.
Note - If you do not care or want to use the same variable again in the program, then you can follow 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 marks of each subjects, something similar to this way:
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, array not only plays a crucial role in storing multiple values using a single variables. It also helps in accessing items/elements and outputting them in easy and simple way. As you can see, while printing the marks of all 6 subjects, without using array, we have to remember and write separate variable along with separator (,)
Create an Array in JavaScript using 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, then define or initialize elements to it. For example:
const marks = []; marks[0] = 89; marks[1] = 87; marks[2] = 93; marks[3] = 76; marks[4] = 69; marks[5] = 80;
In above JavaScript code snippet, 0, 1, 2, 3, 4, 5 are indexes of array, that can be used to access array elements further.
Note - Since indexing always starts with 0, therefore element at index number [0] refers to the first value, whereas element at index number [1] refers to second value, and so on.
Access Array Elements in JavaScript
After understanding all the concept above this para, I don't think you still need to understand how an array elements be accessed. Anyway, let me tell you, to access an array elements, just use the array name along with index numbers of the elements in this way:
arrayName[index]
For example, to access third element, or element available at index number [2] of 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/update an array further, by changing/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 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 snapshot given below shows the output produced by the above example:
Arrays are Objects in JavaScript
Since arrays are treated as objects in JavaScript, therefore 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 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 Array in JavaScript
In JavaScript, it is not necessary to use same type of value while defining elements to an array. We can use any kind of value, variable and/or object to define an array. For example:
const myArray = [10, "fresherearth", 12.32, true];
Characteristics of Arrays in JavaScript
Here are the list of some important characteristics of arrays in JavaScript:
- Arrays in JavaScript, are re-sizable
- 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 length of an array
- unshift() - add element to beginning of an array
- push() - add new element at the end of an array
- shift() - remove first element from an array
- pop() - remove last element from an array
- indexOf() - get first index of a value in an array
- lastIndexOf() - get 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 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 first element that satisfies given condition
- findIndex() - get index of 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 specified array by filling specified elements
- filter() - filter an array based on 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 »