In this article, you’ll learn how to declare and initialize an array in javascript. In JavaScript, you can declare an Array in several ways. Let's consider the two most common ways: the array constructor and the literal notation.
The Array()
constructor is used to create Array objects. You can declare an array with the "new
" keyword to instantiate the array in memory.
Here’s how you can declare new Array()
constructor:
Let's take an example to understand this:
let arr = new Array();
console.log(arr);
//Output => []
let arr1 = new Array (10, 20, 30, 40, 50);
console.log(arr1);
//Output => [10, 20, 30, 40, 50]
let arr2 = new Array (3);
console.log(arr2);
//Output => [undefined, undefined, undefined]
let arr3 = new Array ('3');
console.log(arr3);
//Output => ["3"]
Note: Be careful when using new Array()
. It complicates the code and can also produce some unexpected results.
The preferred way is to always use the literal syntax with square brackets; its behaviour is predictable for any number of items, unlike Array's.
Let's take an example to understand this:
//Declare an Empty Array
let arr = [];
console.log(arr);
//Output => []
//initiliaze an Array with 5 Elements
let arr1 = [10, 20, 30, 40, 50];
console.log(arr1);
//Output => [10, 20, 30, 40, 50]
//initiliaze an Array with 1 Elements
let arr2 = [10];
console.log(arr2);
//Output => [10]
//initiliaze an Array with 5 Elements
let arr3 = ['3','5','7','9','11'];
console.log(arr3);
//Output => ["3", "5", "7", "9", "11"]
var arr4 = []; // array of size 0
arr4[2] = 12; // arr4 is now size 3:
console.log(arr4)
//Output => [undefined, undefined, 12]
I hope this article will help you to understand how to declare and initialize an array in javascript.
Share your valuable feedback, please post your comment at the bottom of this article. Thank you!
Comments