JavaScript Array
Last Updated on May 08, 2022JavaScript Array
The Array object is one of the eight fundamental data types in JavaScript. It is used to store a list of values, each identified by an index or key. The values can be any type, including other arrays.
Array objects are created using the array literal notation, which consists of square brackets containing zero or more comma-separated values.
Let's take a look at a code example of an array
//We can use any variable keywords to define the array
const nameOfArray = [value1, value2, value2];
let nameOfArray = [value1, value2, value2];
var nameOfArray = [value1, value2, value2];
Let's see the real world example. Let's create an array for list of computer programming languages.
//We can give a name of the variable like this: list_of_programming_languages or listOfProgrammingLang
var listOfProgrammingLang = [
"JavaScript",
"Python",
"Csharp",
"AspDotNet",
"HTML"
];
console.log(listOfProgrammingLang);
//Output: ["JavaScript", "Python", "Csharp", "AspDotNet", "HTML"]
Another way to create an array
var listOfProgrammingLang = [];
listOfProgrammingLang[0] = "JavaScript";
listOfProgrammingLang[1] = "Python";
listOfProgrammingLang[2] = "Csharp";
listOfProgrammingLang[3] = "AspDotNet";
listOfProgrammingLang[4] = "HTML";
console.log(listOfProgrammingLang);
//Output: ["JavaScript", "Python", "Csharp", "AspDotNet", "HTML"]
We can also create an array with new keyword.
var listOfProgrammingLang = new Array ("JavaScript","Python","Csharp","AspDotNet","HTML");
console.log(listOfProgrammingLang);
//Output: ["JavaScript", "Python", "Csharp", "AspDotNet", "HTML"]
However we have created the array somehow we have to access the value of an array? We can access the array value by referring to the index number.
var listOfProgrammingLang = ["JavaScript","Python","Csharp","AspDotNet","HTML"];
console.log( listOfProgrammingLang[0] ); //JavaScript
console.log( listOfProgrammingLang[1] ); //Python
console.log( listOfProgrammingLang[2] ); //Csharp
console.log( listOfProgrammingLang[3] ); //AspDotNet
console.log( listOfProgrammingLang[4] ); //HTML
Let's see how we can use For loop to achieve the same result
var listOfProgrammingLang = ["JavaScript","Python","Csharp","AspDotNet","HTML"];
for(var i = 0; i < listOfProgrammingLang.length; i++){
console.log( listOfProgrammingLang[i] );
//Output: JavaScript, Python, Csharp, AspDotNet, HTML
}