Using an array literal is the easiest way to create a new Array in JavaScript. There is no need to use the new Array() way to create Array.
const array_name = [item1, item2, ...];
// Using array literal notation
let myArray = [];
// Using Array constructor
let myArray2 = new Array();
You can also create an array and then assign the elements.
const cars = [];
cars[0]= "AAA";
cars[1]= "BBB";
cars[2]= "CCC";
Create a new Array JavaScript
Simple example code Arrays can be created using the literal notation: You can also initialize an array with values by passing them as comma-separated elements within the square brackets
<!DOCTYPE html>
<html>
<body>
<script>
let fruits = ['Apple', 'Banana'];
console.log(fruits.length);
console.log(fruits);
</script>
</body>
</html>
Output:
Array constructor with multiple parameters
If more than one argument is passed to the constructor, a new Array
with the given elements is created.
let fruits = new Array('Apple', 'Banana');
console.log(fruits.length); // 2
console.log(fruits[0]); // "Apple"
You can access and modify elements in the array using their index. The index starts from 0, so the first element is at index 0, the second at index 1, and so on. Here’s an example:
let myArray = [1, 2, 3, 4, 5];
console.log(myArray[0]); // Output: 1
myArray[2] = 10;
console.log(myArray); // Output: [1, 2, 10, 4, 5]
These are just the basics of creating and working with arrays in JavaScript. There are many other operations and methods available for arrays, such as push
, pop
, splice
, and more.
Comment if you have any doubts or suggestions on this JS array code.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version