An array is a collection of items of the same data type stored in memory.to know more about arrays the read here.
We can create arrays mainly in 3 ways in LWC.
Create Array using assignment operator in LWC
This is most common and recommended way of creating arrays in lightning web components.
// Creating an empty array
fruitsArray1 = [];
// Creating an array with some data
fruitsArray2 = ["Apple", "Banana"];
Create Array using constructor in LWC
another way of creating an array in lwc is using constructor.
// Creating an empty array
fruitsArray3 = new Array();
// Creating an array with some data
fruitsArray4 = new Array("Apple", "Banana", "Orange");
Create Array using Array.of() in LWC
One more way of creating an array is using Array.of() method.
// Creating an empty array
fruitsArray5 = Array.of();
// Creating an array with some data
fruitsArray6 = Array.of("Apple", "Banana", "Orange","Mango");
we have created a sample lightning web component having all these 3 ways to create an array.
CreatingAnArray.html
<template>
<lightning-card title="Create an array assignment" icon-name="custom:custom14">
<ul class="slds-m-around_medium">
<template for:each={fruitsArray2} for:item="fruit">
<li key={fruit}>
{fruit}
</li>
</template>
</ul>
</lightning-card>
<lightning-card title="Create an array using constructor" icon-name="custom:custom14">
<ul class="slds-m-around_medium">
<template for:each={fruitsArray4} for:item="fruit">
<li key={fruit}>
{fruit}
</li>
</template>
</ul>
</lightning-card>
<lightning-card title="Create an array using Array.of()" icon-name="custom:custom14">
<ul class="slds-m-around_medium">
<template for:each={fruitsArray6} for:item="fruit">
<li key={fruit}>
{fruit}
</li>
</template>
</ul>
</lightning-card>
</template>
CreatingAnArray.js
import { LightningElement } from 'lwc';
export default class CreatingAnArray extends LightningElement {
//Create Array using assignment operator
//-------------------------------------
// Creating an empty array
fruitsArray1 = [];
// Creating an array with some data
fruitsArray2 = ["Apple", "Banana"];
//Create Array using constructor
//-------------------------------------
// Creating an empty array
fruitsArray3 = new Array();
// Creating an array with some data
fruitsArray4 = new Array("Apple", "Banana", "Orange");
//Create Array using Array.of() method
//-------------------------------------
// Creating an empty array
fruitsArray5 = Array.of();
// Creating an array with some data
fruitsArray6 = Array.of("Apple", "Banana", "Orange","Mango");
}
CreatingAnArray component output:
Also found above code in Tech Shorts Git repo