Make Money Online HTML PHP JAVASCRIPT 12: How to Create Arrays in JavaScript | Store Multiple Data in an Array | JavaScript Tutorial

12: How to Create Arrays in JavaScript | Store Multiple Data in an Array | JavaScript Tutorial

12: How to Create Arrays in JavaScript | Store Multiple Data in an Array | JavaScript Tutorial post thumbnail image


An array is a data structure that allows you to store multiple data items in a single variable. In JavaScript, you can create arrays using the Array constructor, or you can use the Array literal notation.

To create an array using the Array constructor, you need to specify the type of data that the array will store, and the number of items that the array will store. For example, the following code creates an array of numbers:

var numbers = new Array(5);

This code creates an array that can store up to 5 numbers.

To create an array using the Array literal notation, you need to specify the type of data that the array will store, and the number of items that the array will store, between square brackets. For example, the following code creates an array of numbers:

var numbers = [1, 2, 3, 4, 5];

This code creates an array that can store up to 5 numbers.

You can also create arrays that store objects or strings. For example, the following code creates an array that stores objects:

var objects = [{name: “Bob”}, {name: “John”}];

This code creates an array that can store up to 2 objects.

You can also create arrays that store strings. For example, the following code creates an array that stores strings:

var strings = [“Hello”, “World”];

This code creates an array that can store up to 2 strings.

You can access the items in an array using the index number of the item. The first item in an array has an index of 0, the second item has an index of 1, and so on. For example, the following code prints the name of the first object in the objects array:

console.log(objects[0].name);

This code prints “Bob”.

You can also use the for…in loop to iterate through the items in an array. The for…in loop will iterate through the indexes of the array, as well as the values of the array. For example, the following code prints the name of each object in the objects array:

for (var i in objects) {

console.log(objects[i].name);

}

This code prints “Bob” and “John”.

Related Post