In JavaScript, an array is a collection of values that can be of any type, including numbers, strings, objects, and other arrays. You can create an array in JavaScript using several methods.
Not a Medium member? Read this article here
Method 1: Using array literal notation One of the easiest ways to create an array in JavaScript is to use an array literal notation, which involves enclosing a comma-separated list of values within square brackets.
const myArray = [1, 2, 3, "four", { name: "John" }];
console.log(myArray); // Output: [1, 2, 3, "four", { name: "John" }]
Method 2: Using the Array constructor You can also create an array using the Array
constructor. This method involves calling the Array
constructor with the new
keyword and passing the values to be included in the array as arguments.
const myArray = new Array(1, 2, 3, "four", { name: "John" });
console.log(myArray); // Output: [1, 2, 3, "four", { name: "John" }]
Method 3: Creating an empty array and adding elements later You can create an empty array and add elements to it later using the array’s push()
method.
const myArray = [];
myArray.push(1);
myArray.push("two");
myArray.push({ name: "John" });
console.log(myArray); // Output: [1, "two", { name: "John" }]