Declaration and Initialization using Array Constructor in JavaScript

Array Constructor in JavaScript

The Array() constructor is a built-in JavaScript function used to create a new array object. It can be called with or without the new keyword. When called without any arguments, the Array() constructor creates an empty array with no elements. "Array

Array:

  • In JavaScript, An array is one of the most commonly used data types.
  • It stores multiple values and elements in one variable.
  • These values can be of any data type — You can store a string, number, boolean, and other data types in one variable.
  • There are two standard ways to declare an array in JavaScript. - (constructor or the literal notation).
  • Arrays in JavaScript can dynamically change in size, meaning you can add or remove elements as needed

syntax:

new Array()
new Array(newElement)
new Array(newElement, newElement2)
new Array(newElement, newElement2, /* … ,*/ newElemenet10)
new Array(arrayLength) //number type only
Note: Array() can be called with or without new. Both create a new Array instance. Array()
Array(newElement)

Declaration

constructor
const newArray = new Array(); console.log(newArray); // Output: []
literal notation
let notationArray = [];
console.log(notationArray); // Output: []
Array declared both ways.

Initialization

You can also pass one or more arguments to the Array() constructor, specifying the initial values of the array elements

constructor

const newArray = new Array(5, 6, 7); console.log(newArray); // Output: [5, 6, 7]

 iteral notation

let notationArray = [2, 3, 4];
console.log(notationArray); // Output: [2, 3, 4]
Note: that when passing a single numeric argument to the Array() constructor, it specifies the initial length of the array Create arrays with a dynamic length by passing a numeric argument that specifies the initial length of the array For Ex, const newArray = new Array(10); // creates an array with length 10 console.log(newArray); // Output: [empty × 10]    If you pass a single non-numeric argument to the Array() constructor, it will be treated as the initial value of the first element of the array.
constnewArray = new Array(true);  console.log(newArray); // [true] 
  • It is not compulsory to add new, as both Array() and new Array() perform the same task.
const newArray= Array("hpkingdom.com", '100%', true);  console.log(newArray);  // ["hpkingdom.com", '100%', true] 
  Array-like Objects: The Array() constructor can also be used to convert array-like objects (objects with a length property and indexed elements) into actual arrays. For Ex:
const arrayObject = { 0: "a", 1: "b", length: 2 };
const myArray = Array.from(arrayObject);
console.log(myArray); // Output: ["a", "b"]
  In this article, you have learned how to Initialize an array constructor in JavaScript.