Arrays in JavaScript | LWC JavaScript Tutorial | Peoplewoo Skills

27.11.25 10:12 AM - By Peoplewoo

Arrays are one of the most essential data structures in JavaScript and are used everywhere in Lightning Web Components (LWC). Whether you're rendering a list in HTML, processing Apex data, iterating over records, or building UI for dynamic components—arrays are always involved.

This in-depth guide (3000+ words) will take you from the fundamentals of JavaScript arrays to advanced patterns, performance techniques, LWC-specific use cases, and industry-level best practices.


What Is an Array in JavaScript?

An array is an ordered list-like object used to store multiple values in a single variable. In JavaScript, arrays are extremely flexible — they can store:

  • Numbers
  • Strings
  • Objects
  • Booleans
  • Functions
  • Other Arrays (Nested Arrays)

Basic Example

 const skills = ["JavaScript", "LWC", "Apex", "Data Cloud"]; console.log(skills); 

Watch Our Video Tutorial


How JavaScript Stores Arrays (Internal Working)


JavaScript arrays are not traditional arrays like C/C++. Internally, arrays in JS behave more like dynamic hash maps:

  • Index → Key
  • Value → Stored Against Key
  • Resizable → Automatically increases size

This makes JavaScript arrays extremely powerful and easy to use, but it also means:

  • They may not be the fastest for heavy numeric operations
  • Indexes don’t always represent continuous memory blocks
  • Performance varies depending on usage pattern

Creating Arrays


1. Array Literal (Most Common)

 const fruits = ["Apple", "Banana", "Mango"]; 

2. Using the Array Constructor

 const numbers = new Array(10, 20, 30); 

3. Empty Array + Adding Later

 const list = []; list.push("Peoplewoo Skills"); 

4. Mixed Data Types

 const mixed = [1, "Amit", true, { role: "Developer" }, [1, 2, 3]]; 

Accessing Elements & Indexing

 const colors = ["Red", "Green", "Blue"]; console.log(colors[0]); 
// Red console.log(colors[2]); // Blue 

Length Property

 console.log(colors.length); // 3 

Last Element

 console.log(colors[colors.length - 1]); 

Mutating vs Non-Mutating Array Methods

Mutating MethodsNon-Mutating Methods
push(), pop(), shift(), unshift()map(), filter(), slice()
sort(), reverse(), splice()concat(), includes(), find()


Important for LWC: Avoid mutating arrays directly because it may not trigger UI updates. Use non-mutating patterns or assign new arrays.


Most Important Array Methods (Detailed Explanation)


1. push() – Add to end (Mutates)

 const items = [1, 2]; items.push(3); // [1, 2, 3] 

2. pop() – Remove from end

 items.pop(); 

3. unshift() — Add to start

 items.unshift(0); // [0,1,2] 

4. shift() — Remove from start

 items.shift(); 
 

High-Level Functional Array Methods


map() — Transform each element

 const doubled = [1,2,3].map(num => num * 2); console.log(doubled); // [2,4,6]
 

filter() — Keep only matching items

 const filtered = [1,2,3,4].filter(num => num % 2 === 0); // [2,4] 

find() — Return first matching element

 const found = [10,20,30].find(x => x > 15);  // 20 

every() — Check if all match

 [2,4,6].every(x => x % 2 === 0); // true 

some() — Check if at least one matches

 [1,3,5,6].some(x => x % 2 === 0); // true 

findIndex() — Return index of first match

 [10,20,30].findIndex(x => x === 20); // 1 

reduce() — The Most Powerful Method

Reduce converts an entire array into a single value: number, object, string, or new array.


Example: Sum

 const sum = [1,2,3].reduce((acc, curr) => acc + curr, 0); // 6 

Example: Count Occurrences

 const names = ["Amit", "Amit", "Suraj"];
 const count = names.reduce((acc, name) =>
 {     acc[name] = (acc[name] || 0) + 1;   
  return acc; }, {}); 

Sorting Arrays


Default Sorting (Alphabetical)

 ["Banana", "Apple"].sort(); 
 

Numeric Sorting

 [10,5,100].sort((a,b) => a-b); 

Sorting Objects

 const contacts = [   {name:"Amit", age: 30}, 
  {name:"Suraj", age:25} ]; contacts.sort((a,b) => a.age - b.age); 

Spread Operator (…) – Modern Array Power


Clone Array

 const arr = [1,2,3]; const cloned = [...arr]; 

Merge Arrays

 const all = [...arr1, ...arr2]; 

Add Items Without Mutation

 const updated = [...arr, 4]; 

Rest Operator (…) – Collect Remaining Values

 const [first, ...rest] = [1,2,3,4]; console.log(rest); // [2,3,4] 

Array Destructuring

 const [a, b] = ["LWC", "Apex"]; console.log(a); // LWC 

Skipping Values

 const [x,,y] = [10,20,30]; 

Multidimensional Arrays

 const matrix = [   [1,2],   [3,4] ]; console.log(matrix[1][0]); // 3 

Immutability in LWC — Critical Concept


Avoid mutating arrays like below:

 // Bad for LWC reactivity this.items.push("New"); 

Always use:

 // Good this.items = [...this.items, "New"]; 

Working with Arrays of Objects

Updating an object inside an array


 this.contacts = this.contacts.map(contact =>
     contact.Id === selectedId         ? { ...contact, status: "Updated" } 
        : contact ); 

Removing an item

 this.contacts = this.contacts.filter(c => c.Id !== selectedId); 

Performance Tips for Arrays


  • Use map() and filter() instead of loops whenever possible
  • Prefer spread operator over JSON cloning
  • Avoid sort() repeatedly — it mutates
  • Use find() instead of filtering entire array when only one match is needed
  • Avoid deeply nested arrays (hard to debug)
  • Use for loops only for performance-sensitive tasks

Best Practices Summary

  • Use const for arrays to avoid accidental reassignment
  • Prefer immutable patterns in LWC
  • Use map, filter, reduce instead of writing manual loops
  • Avoid using splice() directly (mutates)
  • Use for:each with key attributes like Id
  • Always clone arrays before modifying them

Frequently Asked Questions (FAQ)

1. Are arrays mutable in JavaScript?

Yes, but LWC prefers immutable patterns for reactivity.

2. Can arrays store objects?

Yes, objects, arrays, and even functions.

3. What is the best way to clone an array?

Use: [...array]

4. Should I use map() instead of forEach()?

Use map() when you want to create a new array. Use forEach() when you don’t need a new array.

5. How do arrays trigger UI updates in LWC?

By assigning a new array reference, not mutating the existing one.

Conclusion

Arrays are extremely powerful in JavaScript and essential for developing modern Lightning Web Components. From rendering lists to processing Apex results, filtering records, transforming data, and managing UI — arrays form the backbone of dynamic LWC development.

Mastering arrays will help you write cleaner, faster, and more efficient Salesforce components.


More SFDC Resources


Start your SFMC journey today — join our Live Training 

Need help? Chat with us on WhatsApp anytime.

Learn. Practice. Get Certified. Succeed with Peoplewoo Skills.

Peoplewoo

Peoplewoo

Peoplewoo Consulting Private Limited
https://www.peoplewoo.com/