LWC – JavaScript Basics Questions
JavaScript is the foundation of Lightning Web Components development, providing the dynamic behavior and interactivity that makes modern web applications possible. These questions cover essential JavaScript concepts required for LWC development including ES6+ features, arrow functions, promises, async/await, modules, destructuring, spread operators, array methods, object manipulation, error handling, and debugging techniques. Mastering these fundamentals is crucial for building efficient and maintainable LWC components.
JavaScript Basics for LWC - Q&A
- Q1. What are the key JavaScript concepts essential for LWC development?
Ans: Core concepts include: - ES6+ features (classes, modules, arrow functions) - Asynchronous programming (Promises, async/await) - Template literals (`${variable}` syntax) - Destructuring assignments - Spread/Rest operators - Array methods (map, filter, reduce) Example:// ES6 class class DataService { constructor(apiEndpoint) { this.apiEndpoint = apiEndpoint; } async fetchData() { try { const response = await fetch(this.apiEndpoint); return await response.json(); } catch(error) { console.error('Fetch error:', error); throw error; } } } // Template literals const message = `Hello ${userName}, you have ${notificationCount} notifications`; // Destructuring const {name, email} = userObject; const [first, second] = arrayValues; // Spread operator const combinedArray = [...array1, ...array2]; const clonedObject = {...originalObject};
- Q2. How does JavaScript's 'this' keyword work in LWC?
Ans: In LWC: - 'this' refers to the component instance - Arrow functions preserve 'this' context - Event handlers need special attention Example:// Arrow function preserves 'this' handleClick = () => { // 'this' correctly references component this.value = 'Clicked'; this.dispatchEvent(new CustomEvent('notify')); } // Regular function may lose 'this' context handleClick() { // 'this' may be undefined in event handlers // Not recommended for event handlers } // Binding 'this' in constructor constructor() { super(); this.handleClick = this.handleClick.bind(this); } handleClick() { this.value = 'Clicked'; }
- Q3. Explain how Promises are used in LWC.
Ans: Promises handle async operations like: - Apex method calls - Fetch API requests - Timeout operations Example:fetchData() { return new Promise((resolve, reject) => { getApexData({ param: this.recordId }) .then(result => { resolve(result); }) .catch(error => { reject(error); }); }); } // Using promises with then/catch this.fetchData() .then(result => { this.data = result; }) .catch(error => { this.error = error.body.message; }); // Chaining promises getApexData() .then(result => processResult(result)) .then(processed => validateData(processed)) .then(valid => this.data = valid) .catch(error => this.handleError(error));
- Q4. What are JavaScript modules in LWC context?
Ans: Modules allow code organization: - Single-file components (.js files) - Named exports:// utils.js export function formatCurrency(value) { return new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }).format(value); } export const MAX_VALUE = 100; export class DataProcessor { static process(data) { // processing logic return data; } }
- Default exports:export default class Calculator { static add(a, b) { return a + b; } }
- Import syntax:import { formatCurrency, MAX_VALUE, DataProcessor } from 'c/utils'; import Calculator from 'c/calculator';
- Q5. How do you handle errors in LWC JavaScript?
Ans: Best practices: - Try/catch blocks:try { this.data = await getApexData(); } catch(error) { this.error = error.body ? error.body.message : error.message; console.error('Error fetching data:', error); }
- Error boundaries:renderedCallback() { if(this.error) { this.template.querySelector('.error').classList.remove('slds-hide'); } }
- Custom error handling:handleError(error) { // User-friendly error messages if(error.body && error.body.message) { this.errorMessage = `Data error: ${error.body.message}`; } else { }
- Q13. How would you implement array chunking?
Ans: Breaking into smaller arrays:function chunkArray(array, size) { return Array.from( { length: Math.ceil(array.length / size) }, (_, i) => array.slice(i * size, i * size + size) ); }
- Q14. How do you use findIndex() and splice() together?
Ans: Modifying arrays by index:const index = items.findIndex(item => item.id === targetId); if (index !== -1) { items.splice(index, 1); // Remove item items.splice(index, 0, newItem); // Insert item }
- Q15. How would you convert array to object?
Ans: Transformation patterns:// Using reduce() const obj = array.reduce((acc, item) => { acc[item.id] = item; return acc; }, {}); // Using Object.fromEntries() const obj = Object.fromEntries( array.map(item => [item.key, item.value]) );
- Q16. How do you handle nested array operations?
Ans: FlatMap and recursion:// FlatMap example const allTags = articles.flatMap(article => article.tags); // Recursive flatten function flattenDeep(arr) { return arr.reduce((flat, item) => flat.concat(Array.isArray(item) ? flattenDeep(item) : item), []); }
- Q17. How would you implement array memoization?
Ans: Performance optimization:const memoizedProcess = () => { const cache = new Map(); return (array) => { const key = JSON.stringify(array); if (cache.has(key)) return cache.get(key); const result = expensiveOperation(array); cache.set(key, result); return result; }; };