;

How to Declare and Initialize an Array in Javascript


Tutorialsrack 20/11/2021 Jquery Javascript

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 new Array() Constructor

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 arr = new Array(); - declare an empty array
  • let arr = new Array(10,20,30); - array declare with three elements: 10,20,30
  • let arr = new Array(10); - ten empty elements in array: ,,,,,,,,,
  • let arr = new Array('5'); - an array with 1 element: ‘5’

Let's take an example to understand this:

Example - Using new Array() Constructor
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"]

The Literal Notation

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 arr = []; - an empty array
  • let arr = [10]; - initialized array
  • let arr = [10,20,30]; - three elements in the array: 10,20,30
  • let arr = ["10", "20", "30"]; - declares the same: ‘10’,’20’,’30’

Let's take an example to understand this:

Example - Using Literal Notation
//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!


Related Posts



Comments

Recent Posts
Tags