Create array literal
Create Array Literal
An array is a collection of values stored in a single variable. In JavaScript, arrays are created using array literals, which are a list of comma-separated values enclosed in square brackets [].
Example:
var fruits = ['apple', 'banana', 'orange', 'kiwi'];
In this example, we have created an array of fruits. The values 'apple', 'banana', 'orange', and 'kiwi' are enclosed in square brackets [] and separated by commas. The array is assigned to the variable 'fruits' using the assignment operator (=).
There are multiple ways to create an array literal in JavaScript:
- You can create an empty array by providing no values inside the square brackets.
- You can create an array with a single value by providing only one value inside the square brackets.
- You can create a multidimensional array by nesting arrays inside other arrays.
Empty Array:
var emptyArray = [];
In this example, we have created an empty array. Since there are no values inside the square brackets [], the array is empty.
Array with a Single Value:
var singleValueArray = ['hello'];
In this example, we have created an array with a single value. The value 'hello' is enclosed in square brackets [] and assigned to the variable 'singleValueArray'.
Multidimensional Array:
var multidimensionalArray = [['John', 'Doe'], ['Jane', 'Doe']];
In this example, we have created a multidimensional array. The array contains two nested arrays, each containing two values. The array is assigned to the variable 'multidimensionalArray' using the assignment operator (=).