JavaScript Concepts for LWC
1. LWC — display Account and related Contacts on click of a button.
Answer :
// apex class
@AuraEnabled
public static List<Account> getAccountsWithContacts() {
return [SELECT Id, Name, (SELECT Id, FirstName, LastName, Email FROM Contacts) FROM Account LIMIT 50];
}
// LWC JS
import getAccountsWithContacts from '@salesforce/apex/MyController.getAccountsWithContacts';
accounts = [];
handleLoad() {
getAccountsWithContacts().then(result => { this.accounts = result; }).catch(e => console.error(e));
}
// HTML: <lightning-button label='Load' onclick={handleLoad}></lightning-button>
// <template for:each={accounts} for:item='acc'>...
2. Difference between var, let, and const?
Answer :
var: Function-scoped, hoisted to top of function (initialised as undefined), can be redeclared.
let: Block-scoped, hoisted but not initialised (temporal dead zone), cannot be redeclared in same scope.
const: Block-scoped, must be assigned at declaration, cannot be reassigned (but object properties can change).
Best practice: Always prefer const; use let when reassignment needed; avoid var.
3. Difference between == and ===?
Answer :
== (loose equality): Compares values after type coercion. 0 == false is true, '5' == 5 is true.
=== (strict equality): Compares both value AND type. No coercion. '5' === 5 is false. Always prefer ===.
4. What is hoisting in JavaScript?
Answer :
Hoisting moves variable and function declarations to the top of their scope at compile time. var declarations are hoisted and initialised as undefined. Function declarations are hoisted entirely. let/const are hoisted but not initialised (accessing them before declaration throws ReferenceError — temporal dead zone).
5. What is a closure in JavaScript?
Answer :
A closure is a function that retains access to its outer scope's variables even after the outer function has returned. Common use: factory functions, callbacks with state, module pattern. In LWC, closures are used in event handlers that capture component properties.
6. What is event bubbling vs event capture?
Answer :
Event Capture (Capturing phase): Event travels from root DOWN to target element.
Event Bubbling: Event travels from target element UP to root.
event.stopPropagation(): Stops the event from propagating further (either direction).
event.preventDefault(): Prevents the default browser action.
7. Null vs Undefined in JavaScript?
Answer :
undefined: A variable declared but not assigned a value. typeof undefined === 'undefined'.
null: Intentional absence of value — explicitly assigned. typeof null === 'object' (quirk). Use null to indicate 'no value', undefined is the default for unassigned.
💬 Community Chatter
Loading...🔐
Join the Community Discussion
Login to ask questions, share answers, and connect with other Salesforce professionals.