Friday, September 27, 2024
Google search engine
HomeLanguagesJavascriptJavaScript Array() Constructor

JavaScript Array() Constructor

The Array() constructor is used to create Array objects and the array constructor can be called with or without a new keyword, both can create a new Array.

Syntax:

new Array(Value1, Value2, ...);
new Array(ArrayLength);

Array(Value1, Value2, ...);
Array(ArrayLength);

Parameters: 

  • ValueN: An array initialized by the given value, except in the case where only one value is provided to the array constructor and that value is a number. Unfortunately, the previous condition does not hold true if an array is built using the [ ]operator.
  • arrayLength: If the Value is only one element that is also a number between 0 and 2^32 – 1 then an array object is created with the length property set to the array property.

 

Example 1: In this example, we will use the basic use of the Array() constructor.

Javascript




// Using elements
const array1 = new Array(1, 2, 3, 4, 5)
  
// Using arrayLength
const array2 = new Array(10)
  
console.log(array1);
console.log(array2);


Output:

(5) [1, 2, 3, 4, 5]
(10) [empty × 10]

Example 2: In this example, we will use an array with a string value.

Javascript




const language = new Array("HTML", "CSS", "Javascript");
  
console.log(language.length);
console.log(language[0]);
console.log(language[1]);
console.log(language[2]);


Output:

3
HTML
CSS
Javascript

We have a complete list of Javascript Array() methods, to check those please go through this JavaScript Array Reference article.

Supported Browsers:

  • Chrome 1
  • Edge 12
  • Firefox 1
  • Opera 4
  • Safari 1
Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments