How to create a array in JavaScript?
An array is a non-primitive data type that allows you to store multiple values of different or similar data types at consecutive memory blocks in a single variable. The values stored in an array can be accessed using the indexing syntax starting from zero and going to the array.length-1.
Different ways of creating an array in JavaScript are listed below:
- Using array literal: It is the simple square brackets syntax that is generally used to create arrays in programming languages.
- Using Array constructor: JavaScript provides us with an array constructor to create arrays.
Example: The below example shows how you can create a simple array in JavaScript.
Javascript
// Creating array using array literals const myArr1 = [ "GFG" , 254, true , "JavaScript" ]; console.log(myArr1[0], myArr1[2], myArr1); // Creating array using array constructor const myArr2 = new Array( "GFG" , 2, true ); console.log(myArr2[1], myArr2[2], myArr2); |
Output
GFG true [ 'GFG', 254, true, 'JavaScript' ] 2 true [ 'GFG', 2, true ]
Contact Us