How to use an array as literal In Javascript
Initializing an array using the array literal approach involves directly assigning square brackets [] to a variable. This creates an empty array or populates it with elements enclosed within the brackets, offering a concise and straightforward method for array initialization in JavaScript.
Example: Below is an example of array as literal.
const sports = ["cricket", "football",
"competitive-programming"];
console.log('sports=', sports);
const myArray = [];
console.log('myArray=', myArray);
const score = [420, 10, 1, 12, 102];
console.log('score=', score);
Output
sports= [ 'cricket', 'football', 'competitive-programming' ] myArray= [] score= [ 420, 10, 1, 12, 102 ]
Example 2: The line breaks and new lines do not impact arrays, they store in their normal way.
const sports = ["cricket",
"football",
"competitive-programming"];
console.log('sports=', sports);
const myArray = [];
console.log('myArray=', myArray);
const score = [420, 10, 1,
12, 102];
console.log('score=', score);
Output
sports= [ 'cricket', 'football', 'competitive-programming' ] myArray= [] score= [ 420, 10, 1, 12, 102 ]
How to initialize an array in JavaScript ?
Initializing an array in JavaScript involves creating a variable and assigning it an array literal, which consists of square brackets enclosing optional comma-separated elements. These elements can be of any data type or can be omitted for an empty array.
To initialize an array in JavaScript we can use methods given below:
Table of Content
- Using an array as literal
- Using an array as an object/Array() constructor