Salesforce 100 Experienced Lightning WebComponents (LWC) Interview Questions &Answers

- What is the core architectural difference between Aura and LWC, and why is LWC generally faster?
Answer: Aura is a proprietary component model requiring a layer of abstraction and reflection (heavy use of locker service). LWC is built directly on Web Standards (ES6+, Web Components, Shadow DOM). LWC is faster because it requires far less JavaScript framework code to run and relies on the browser's native capabilities for rendering, parsing, and component isolation. - Explain the role of the Locker Service in LWC and how it enforces security and isolation.
Answer: Locker Service is an architectural layer that enhances security by strictly controlling how components can interact with the global window object and other components. It implements a secure wrapper around objects, only exposing APIs that are deemed safe. In LWC, it primarily works by leveraging Shadow DOM for component isolation, and only allowing interaction with other components via explicit API contracts (public properties and events). - How does LWC utilize the native Web Component standards? Identify two standards LWC heavily leverages.
Answer: LWC is Salesforce's implementation of the Web Components specification. It heavily leverages:- Custom Elements: Defining custom tags in HTML (e.g., <c-my-component>).
- Shadow DOM: Providing encapsulation and scoping for the component's CSS and structure, ensuring isolation from the outside document.
- Describe the LWC Module Lifecycle. When are modules loaded, and how does the browser handle dependencies?
Answer: LWC uses ES Modules for dependency management. Modules are loaded asynchronously by the browser. The entire dependency graph is resolved first. When an LWC component imports another component or module (import { methodName } from 'c/myUtil'), the browser's native module loader handles fetching and executing the imported file once, creating a singleton instance in memory for shared utilities. - Explain the role of the Locker Service in LWC and how it enforces security and isolation.
Answer: The export keyword, when used with default for the main class, marks the entry point of the LWC module. Even if you only have one class, the framework relies on this explicit export default class MyComponent extends LightningElement {} to register the component class definition with the runtime engine. - How does LWC handle the globalThis object or access to the standard global window object?
Answer: LWC restricts direct access to the global window object for security (Locker Service). Instead, developers are encouraged to use specific, secure, exposed APIs. For instance, requestAnimationFrame is accessible, but directly manipulating elements outside the component's scope via global methods is prevented. - Explain the role of the Locker Service in LWC and how it enforces security and isolation.
Answer:: LDS is a declarative data layer that simplifies data operations (CRUD) without requiring Apex code.- Problems Solved: Data caching, component synchronization (when one component updates a record, all others using LDS automatically reflect the change), field-level security, and automatic handling of stale data validation.
- Explain the difference between getRecord and getRecords in the lightning/uiRecordApi and their common use cases.
Answer:- getRecord(recordId, fields): Used to fetch a single record by ID. Ideal for component-level record detail pages or viewing context-specific data.
- getRecords(recordIds, fields): Used to fetch multiple records in a single wire call. Ideal for list views where a batch of records needs to be displayed and managed efficiently.
- When defining fields for LDS, why is using a reference like ACCOUNT_NAME_FIELD preferred over a hardcoded string 'Account.Name'?
Answer: Using imported schema references (import NAME_FIELD from '@salesforce/schema/Account.Name';) is mandatory. This practice ensures compile-time validation. If an SObject or field name is misspelled or removed, the component will fail to compile, catching errors early. Hardcoded strings lead to runtime failures that are difficult to debug. - Describe the standard folder structure required for a basic LWC and the role of its configuration file.
Answer:- Structure: lwc/myComponent/myComponent.html, lwc/myComponent/myComponent.js, lwc/myComponent/myComponent.js-meta.xml.
- Config (.js-meta.xml): This XML file defines the component's metadata, including its API version, whether it's exposed (isExposed), and where it can be used (targets, e.g., App Page, Record Page). It also defines any public configuration properties available in the App Builder (targetConfigs).
- Why do we use the template tag in the HTML file of an LWC?
Answer: The template tag is the root element that defines the LWC's HTML structure. It aligns with the Web Component specification for defining template content. LWC uses this template to clone the content and attach it to the component's Shadow Root upon initialization. - How do you handle conditional rendering in LWC, and what is the difference between if:true and CSS visibility?
Answer:- LWC Directives: Use <template if:true={condition}> and <template if:false={condition}>. The LWC engine completely removes the DOM element and its descendants from the tree if the condition is false.CSS Visibility (display: none): The DOM element remains in the tree, but it is visually hidden.
- Difference: if:true is preferred for performance and logic control, as it reduces the overall DOM size. CSS is used when the element needs to be toggled frequently without the overhead of re-rendering the DOM tree.
- Explain the purpose of the lwc/messageService module in achieving cross-component communication.
Answer: The Lightning Message Service (LMS) is the standard, high-performance solution for communication between components across the application, regardless of their location in the DOM tree (e.g., LWC to Aura, LWC to Visualforce). It implements a Publish-Subscribe pattern using a defined message channel. - When would you use the LightningElement base class over a standard HTML element, and what essential functionality does it provide?
Answer: Every LWC must extend LightningElement. It provides all the necessary LWC framework functionality, including:- Component lifecycle hooks (connectedCallback, renderedCallback).Reactive properties (@api, @track, @wire).Native event dispatching via this.dispatchEvent(new CustomEvent(...)).
- Automatic rendering and change detection.
- What is the significance of the aria-* attributes in LWC development?
Answer: aria-* attributes (Accessible Rich Internet Applications) are crucial for web accessibility. They define roles, states, and properties that screen readers and other assistive technologies can interpret. Salesforce mandates strong accessibility, and LWCs should include these attributes to make interactive elements usable for everyone. - In LWC, why is it considered a bad practice to mutate an array or object received from an external module or @wire?
Answer: Mutating external data breaks the unidirectional data flow and makes debugging state changes extremely difficult. Data received from @wire is read-only (frozen). If you need to modify it, you should first create a deep copy of the data structure and then apply modifications to the copy. - How do you reference static resources (images, libraries) from within an LWC template?
Answer:- Import: Import the static resource name in the JavaScript file using the special prefix @salesforce/resourceUrl.
import MY_IMAGE from '@salesforce/resourceUrl/MyImage';
- Reference in Template: Expose the imported variable to the template and use it with binding.
<img src={myImage} />
- Import: Import the static resource name in the JavaScript file using the special prefix @salesforce/resourceUrl.
- Explain the purpose of the lwc-recipes repository and its relevance to experienced LWC developers.
Answer: The lwc-recipes repository provides numerous examples and best-practice patterns for solving common development tasks using LWC features. Experienced developers use it not just for "how-to," but to ensure they are using the latest, recommended patterns from Salesforce, especially for complex integrations with Apex, LDS, and third-party libraries. - What is the importance of having a hyphen in the component name (e.g., my-component)?
Answer: This is a requirement of the Web Component specification for Custom Elements. A hyphen is mandatory in the tag name to distinguish custom elements from native HTML elements, preventing potential naming conflicts with future HTML elements. - When setting boolean properties on a child LWC, why must you use JavaScript binding (<c-child is-active={true}>) instead of just declaring the attribute (<c-child is-active>)?
Answer: In LWC, boolean values passed via @api properties must be explicitly resolved as JavaScript booleans (true or false). If you only use <c-child is-active>, the HTML parser interprets the existence of the attribute as the string value "is-active", not the boolean true. Binding ensures the correct boolean type conversion. - Detail the difference in usage between @api and @track decorators.
Answer:- @api (Public Property): Used for public properties that an external parent component can set. They are reactive, meaning if the value changes from the parent, the component re-renders.
- @track (Internal/Private Property): Used for private properties that, when changed internally, cause the LWC component to re-render. Since LWC introduced reactive fields (properties without any decorator that are reactive if initialized), @track is primarily needed only for tracking changes on the properties of an object or elements of an array.
- What is the purpose of the CustomEvent constructor in LWC, and what are its three key configuration properties?
Answer: CustomEvent is the standard Web Component mechanism used to dispatch events from a child component to its parent component.- Configuration Properties:
- bubbles: (Boolean) If true, the event will propagate up the DOM tree.
- composed: (Boolean) If true, the event can pass through the Shadow DOM boundary.
- detail: (Object) An optional payload object containing the data to be passed with the event.
- Configuration Properties:
- Explain the difference between event bubbling and composition in LWC event dispatching.
Answer:- Bubbling: Controls vertical propagation. If bubbles: true, the event travels up the DOM tree, and any ancestor component in the Light DOM can handle it.
- Composition: Controls horizontal propagation across the Shadow DOM boundary. If composed: true, the event can escape the child component's Shadow DOM and continue its bubbling path into the parent's Shadow DOM or the Light DOM. For LWC-to-LWC communication, both bubbles: true and composed: true are often required for ancestor components to listen.
- How do you expose a public method (imperative API) from a child LWC that a parent component can call?
Answer:- Decorate the method in the child's JS file with the @api decorator.In the parent's JS file, use a querySelector to get a reference to the child component.
- Call the method directly on the child reference: this.template.querySelector('c-child-comp').childMethod(params);
- When implementing a property setter with @api, what is the benefit of using the setter for validation or data transformation?
Answer: Using an @api setter allows you to intercept the value passed by the parent before it is assigned to the component's internal property. This is ideal for:- Validation: Ensuring the passed value is in the correct format or range (e.g., if a number is negative).
- Transformation: Applying immediate formatting or calculation (e.g., converting a currency string to a number) and storing the transformed value in a private internal property.
- Describe the implementation steps for using Lightning Message Service (LMS) for sibling communication.
Answer:- Define Channel: Create a messageChannel file (XML) under the messageChannels folder.Import: Import the channel and the required functions (publish, subscribe, MessageContext) into both sibling components.Subscriber (Receiver): Import MessageContext, use @wire(MessageContext) to get the context, and call subscribe in connectedCallback to listen to the channel. Store the subscription ID.
- Publisher (Sender): Import MessageContext and call publish(messageContext, channel, payload) when the data needs to be broadcasted.
- Why should you always unsubscribe from an LMS channel in the disconnectedCallback()?
Answer: Failing to unsubscribe leads to a memory leak. The component is removed from the DOM, but the LMS framework still holds a reference to the component's subscription handler. This prevents the component instance and its associated scope from being garbage collected. Unsubscribing releases that reference. - Explain the pattern for achieving Pub/Sub communication without using LMS, assuming components are far apart in the DOM tree (deprecated, but necessary to understand).
Answer: The original pattern used a global Pub/Sub utility module.- Utility Module: A simple JS module exports a singleton with subscribe(eventName, callback) and fire(eventName, payload) methods. This module internally uses an EventEmitter (or a Map of callbacks).
- Communication: Components import this utility. Publisher calls fire(); subscribers call subscribe() and implement cleanup in disconnectedCallback().
- When passing a complex object via an @api property, how can the child component react to changes on the properties of that object, even if the reference itself doesn't change?
Answer:- The @api property must be initialized as an ES6 reactive field (no decorator).The parent must pass a new reference of the object when any property changes (i.e., the parent must clone and replace the entire object). LWC only tracks changes to the object reference.
- Alternative: Use the @track decorator on a private property. When the @api setter is called, assign the passed object to the @track property. When a deep mutation is expected, use a setter and force a re-render by creating a copy of the object and assigning it to a private tracked property.
- What is the significance of the key attribute when rendering lists with for:each?
Answer: The key attribute (must be unique for each list item) is essential for efficient DOM diffing and re-rendering. It allows the LWC engine to uniquely identify list items. When the data changes, the engine can quickly determine if an item was added, removed, or simply moved, enabling it to update only the necessary parts of the DOM rather than re-rendering the entire list. - In LWC, what is the safest way to pass a large volume of data from a parent component to a child without impacting the parent's reactivity?
Answer: Pass the record ID(s) via an @api property, and let the child component handle the data fetching via its own @wire call to LDS (getRecord) or Apex. This decouples the child's data requirements and maintains the single responsibility principle. - When handling an input event in LWC, how do you correctly read the value from the event object, and why should you avoid accessing e.target.value directly in asynchronous code?
Answer:- Reading Value: Access the value via the event object: event.detail.value (for standard LWC inputs) or event.target.value (for native inputs).
- Async Avoidance: The event object, e, is a synthetic event and its properties might be pooled (reused/nullified) by the framework shortly after the synchronous event handler finishes. If you try to access e.target.value inside a setTimeout or a Promise chain, the properties might be lost. If you need the value asynchronously, you must extract and save the required properties before the asynchronous call: const value = event.target.value;.
- Why do we use the data-id attribute in LWC, and how is it leveraged for dynamic event handling?
Answer: data-id is a standard HTML5 data attribute that stores custom data associated with an element. In LWC, it's frequently used to:- Identify Context: When a user clicks an element in a list (for:each), the event handler can read event.target.dataset.id to determine which specific item was clicked, passing its ID to the main logic.
- Query Selection: Used with this.template.querySelector('[data-id="myId"]') for imperatively finding elements.
- In the context of the LWC data flow, what is a "hot" stream versus a "cold" stream?
Answer:- Cold Stream (Apex @wire): The data flow is passive. The component must explicitly request the data (by wiring a property or function) to initiate the data stream. The connection is established only when the component is ready.
- Hot Stream (LMS or eventListeners): The data flow is active and broadcasted. The data is being published continuously or whenever an event occurs, regardless of whether a subscriber is currently listening. Subscribers only start receiving data when they explicitly connect.
- When using getRecord with the @wire decorator, how does LWC handle field-level security (FLS) and object-level security (OLS)?
Answer: The @wire service for LDS automatically respects FLS and OLS at the component level.- OLS: If the user doesn't have access to the object, the wire service returns an error.
- FLS: If the user doesn't have access to a requested field, the record data is returned, but the value for the inaccessible field will be null or undefined, effectively hiding the secure data without throwing an error.
- When developing a third-party library LWC, how can you ensure the property names passed in by the consumer are correctly handled in LWC's camelCase-to-kebab-case conversion?
Answer:- API Naming: In the child component's JS, the public property is declared in camelCase (@api myPublicProperty).Template Naming: In the parent component's HTML, the attribute must be written in kebab-case (my-public-property).
- Conversion: The LWC compiler automatically maps the kebab-cased attribute to the camel-cased property name, making the conversion seamless. Experienced developers must be aware of this distinction.
- How would you dispatch a custom event that can be handled by an Aura component higher up the hierarchy?
Answer: For an Aura component to handle a standard LWC event, the event must penetrate the Shadow DOM boundary and bubble up in the Light DOM.- Configuration: The CustomEvent must be configured with bubbles: true AND composed: true.
- Handling: The Aura component listens using the standard format: <c:myChild onmyevent="{!c.handleMyEvent}">.
- Explain the utility of the currentRecordId property when using a component on a record page.
Answer: currentRecordId is automatically provided by the framework when an LWC is placed on a Record Page. It is used to get the context of the record currently being viewed. You can access it via the @api recordId public property, which the framework automatically populates. - In LWC, when is it appropriate to use a property or method from the base LightningElement class without explicitly calling super?
Answer: LWC is a class extension, so you can call properties and methods inherited from LightningElement directly using this. Examples include:- this.template.querySelector(...)this.dispatchEvent(...)
- this.classList.add(...)
- How can you ensure that a Promise chain within an LWC (e.g., after an imperative Apex call) uses the correct component context (this)?
Answer: The this context is often lost inside Promise callbacks (.then()). The standard ES6 solution, which LWC fully supports, is to use Arrow Functions (() => {}). Arrow functions lexically bind this to the context in which they are defined (the LWC instance), preserving the correct component context throughout the chain. - Describe the flow and purpose of the three main lifecycle hooks: constructor, connectedCallback, and renderedCallback.
Answer:- constructor(): Runs first. Used for initializing private fields/variables. Critical Rule: Must call super() first. Cannot access attributes or the component's internal DOM (this.template).connectedCallback(): Runs when the component is inserted into the DOM. Used for initialization logic that requires DOM existence (e.g., calling Apex, registering event listeners, subscribing to LMS).
- renderedCallback(): Runs after the component template has rendered and the component's internal DOM is ready. Critical Rule: Must be used carefully and checked against a flag (this.hasRendered) to prevent infinite rendering loops, as it fires after every re-render.
- What causes an LWC component to re-render? List at least three triggers.
Answer:- A public property (@api) value changes (set by the parent).A reactive field (field initialized with a value, with or without @track) is assigned a new value.A wired property or function receives new data (e.g., a successful @wire response).
- An explicit call to the component's render() method (rarely used).
- Why is it critical to use a flag or check inside renderedCallback()? Provide an example of how to implement the check.
Answer: renderedCallback runs after every re-render cycle. If the logic inside it modifies a reactive property, it triggers another re-render, creating an infinite rendering loop that crashes the browser/component.- Example Implementation:
hasRendered = false; renderedCallback() {if (!this.hasRendered) {// Logic that should only run once, e.g., third-party library initialization this.hasRendered = true; }}
- Example Implementation:
- What is the difference between an un-decorated field and a field decorated with @track in modern LWC (post-Winter '20)?
Answer: Since Winter '20, any field declared in the LWC class (that is initialized with a value) is automatically reactive.- Un-decorated Field (Reactive Field): Reactive when the entire value is reassigned (e.g., this.count = 5 or this.obj = { new: 'value' }).
- @track: Is required primarily to track changes to the internal properties of an object or elements of an array when the array/object reference itself is not reassigned. (e.g., this.trackedObj.prop = 'new value').
- When does LWC trigger an automatic refresh of a wired Apex method result? List two scenarios.
Answer:- Reactivity Change: When one of the Apex method's parameters (passed via the wire adapter configuration) changes.
- Explicit Refresh: When the component imperatively calls the refreshApex function on the wired provisioned data object.
- Explain the structure of the object returned by the @wire service when wiring an Apex method or LDS call.
Answer: The provisioned data is an object with two mandatory properties:- data: Contains the successfully resolved payload (the records, the string result, etc.). This is undefined if error is populated.
- error: Contains the error object if the call failed (network error, Apex exception, FLS issue). This is undefined if data is populated.
- How do you perform a synchronous calculation based on a reactive property change without relying on an explicit setter or the lifecycle methods?
Answer: Use an ES6 Getter. Getters are functions defined using the get keyword that are evaluated every time the component re-renders. They are ideal for calculated properties that depend on other reactive fields or properties.
@api firstName = ''; @api lastName = '';// Calculated property (runs on every re-render)
get fullName() {return `${this.firstName} ${this.lastName}`;} - Describe the purpose and implementation of the refreshApex function.
Answer: refreshApex is used to imperatively instruct the LWC wire service to re-invoke a previous @wire provision to fetch the latest data from the server/LDS cache, regardless of whether the wire parameters have changed.- Implementation: It takes the wired provisioned value (the object with data and error properties) as its argument: refreshApex(this.wiredResult);
- When is it necessary to use a function reference instead of a property reference for the @wire decorator?
Answer: A function reference is required when you need to perform imperative logic or conditional branching based on the results of the wired call.- Use Case: If you need to transform the data, handle the error, or call another method as soon as the wired data arrives, you wire to a function. If you only need to bind the data directly to the template, you wire to a property.
- How do you handle an unhandled error/exception that occurs within an LWC component's event handler or lifecycle hook?
Answer: Unhandled errors are caught by the LWC framework. By default, they bubble up the component hierarchy. The best practice is to:- Use try...catch blocks within imperative logic (event handlers, Apex callbacks).
- Implement an Error Boundary component at a higher level in the hierarchy.
- What is an LWC Error Boundary, and how is it implemented?
Answer: An Error Boundary is an LWC designed to catch JavaScript errors that occur in its descendant components' lifecycle hooks or rendering phases. It prevents the entire application from crashing.- Implementation: It uses the errorCallback(error, stack) lifecycle hook. When an error is caught, the component can display a fallback UI, log the error, and prevent the affected component from continuing to render.
- When working with Apex and LWC, what is the impact of caching annotation (@Cacheable=true) on the wire service?
Answer: @Cacheable=true on an Apex method:- Enables Wire: It allows the Apex method to be wired using the @wire decorator.Client-Side Caching: It instructs the platform to cache the response on the client side (in the browser) using a unique key derived from the method name and parameters.
- Data Freshness: LWC will first try to serve the result from the cache. If the cache is stale or the parameters change, it makes a new server call. Note: Cacheable methods must be strictly read-only (GET operations) and idempotent.
- In the connectedCallback(), what are the limitations regarding DOM access?
Answer: You cannot reliably access the component's rendered internal DOM (this.template) in connectedCallback(). The component template has not yet been rendered and attached to the Shadow Root. DOM manipulation or queries should be performed in renderedCallback() (with caution) or inside an event handler that fires after the DOM is ready. - How do you use the track property on an array to ensure the component re-renders when a new item is pushed into the array?
Answer:- Declare the array with @track: @track items = [];When mutating, you must force a new reference to trigger reactivity, even though @track is used. Simply calling this.items.push(newItem) might not work reliably, as the array reference is the same.
- Best Practice: Use the Spread Operator to create a new array reference: this.items = [...this.items, newItem];
- When using the error property of a wired function, how can you extract the meaningful error message to display to the user?
Answer: The error object can be complex. You must safely traverse the structure to find the human-readable message:
let message = 'Unknown error';
if (error) {// Check for common Apex structuremessage = error.body?.message || error.message || error.statusText || message}
// Alternatively, check for LDS error structure message = error.body.output.errors[0].message; - What is the difference between wiring to a property (@wire(method, config) property) and wiring to a function (@wire(method, config) function)?
Answer:- Property: The component re-renders upon receiving data, but the developer has no control over the data until after rendering. Simple and declarative.
- Function: The wired function is executed immediately when data arrives (or an error occurs). The developer controls the flow, allowing for immediate data transformation, error logging, or triggering subsequent actions before the next re-render.
- How do you handle changes in the browser history state (back/forward button) within an LWC?
Answer: LWC does not have a native lifecycle hook for this. You must register an event listener in connectedCallback and remove it in disconnectedCallback:- window.addEventListener('popstate', this.handlePopState);
- What is the primary function of the disconnectedCallback() hook? Give two concrete examples of its usage.
Answer: disconnectedCallback() fires when the component is removed from the DOM. Its primary function is cleanup to prevent memory leaks and unnecessary processing.- Examples:
- Calling unsubscribe to remove a listener from the Lightning Message Service (LMS) channel.
- Calling removeEventListener to remove window or document listeners (e.g., popstate or scroll).
- Clearing setInterval or setTimeout timers.
- Examples:
- Why is it discouraged to modify an @api property value inside the child component, even if it's reactive?
Answer: It violates the principle of Unidirectional Data Flow. @api properties are meant to be controlled by the parent. If the child modifies an @api property, it creates side effects that the parent component (and the LWC framework) cannot track, leading to unpredictable state and difficult-to-debug logic. - If you have two different @wire calls that depend on the same reactive property, how can you ensure the second call only executes after the first one returns successfully?
Answer: You cannot directly chain @wire calls declaratively.- Option 1 (Imperative Chaining - Best): Wire the first call to a function. In that function, if error is null, extract the necessary ID from the result and make the second Apex call imperatively (not wired).
- Option 2 (Conditional Wiring): Wire the first result to a property. Use a Getter that checks if the property is populated, and only then return a parameter that feeds the second @wire call.
- What is the fundamental benefit of the Shadow DOM in LWC, and how does it affect CSS styling?
Answer: The Shadow DOM provides CSS and markup encapsulation. The styles defined within a component's CSS file are scoped only to that component and do not "leak" out to affect the main document or other components (and vice versa). This prevents style conflicts and promotes component reusability.
62.Describe the Shadow DOM Boundary and the concept of "Light DOM" components vs. "Shadow DOM" components.
Answer:- Shadow DOM Boundary: The line of isolation between the component's internal structure and the outside world.Shadow DOM Components: LWCs are primarily Shadow DOM components; their markup is rendered inside a #shadow-root
62.How does LWC's styling model restrict CSS selectors? Why can't you use the universal selector (*) to target all elements?
Answer: LWC's styling is scoped. The engine transforms component CSS selectors to apply a unique identifier to ensure they only affect elements within that component's Shadow DOM. The universal selector is generally disallowed because it violates encapsulation and is highly inefficient. Furthermore, you cannot use selectors like body or div > p to style elements outside the component.
63.Explain the purpose of the Shadow Parts mechanism and when you would use it for styling.
Answer: Shadow Parts (::part(name)) is a standard Web Component mechanism that allows a component author to explicitly define named styling hooks within their Shadow DOM.
Usage: A parent component can use the ::part() pseudo-element in its own CSS to target and style the elements exposed by the child. This is a secure, controlled way to customize a child's internal appearance without breaking encapsulation.
64.What is a "slot," and what is the difference between the default slot and a named slot?
Answer: A slot is a placeholder in a component's HTML where the component's parent can inject content (markup).
Default Slot: Content from the parent that is not explicitly assigned to a named slot will be injected into the single, unnamed <slot></slot> tag.
Named Slot: Content from the parent that uses the slot="slotName" attribute is injected into the corresponding <slot name="slotName"> tag in the child's template.
65. How does the presence of a slot affect the Shadow DOM boundary and the encapsulation of content?
Answer: Content injected into a slot is rendered inside the Shadow DOM of the child component, but its scope and style remain with the parent component. This means the injected content is styled by the parent's CSS, not the child's. The Shadow Boundary remains intact, but the content's origin dictates its styling and event propagation.
66. How would you dynamically create and inject a third-party, non-LWC component (like a chart from a library) into an LWC?
Answer: Since LWC runs in the Shadow DOM and restricts the creation of
Create the chart/element imperatively using standard DOM APIs and inject it into that target div.
64. Explain the purpose of the lwc:dom="manual" directive and its potential performance implications.
Answer: lwc:dom="manual" is an attribute applied to an HTML element (usually a div) within the template. It tells the LWC engine to opt out of managing the contents of that element.
Purpose: Required when integrating complex third-party libraries (like D3 or Chart.js) that need to imperatively manipulate the DOM subtree.
Implications: The LWC framework loses reactivity for that subtree. Any changes must be manually managed using standard DOM APIs, bypassing LWC's efficient diffing algorithm.
65. How do you handle a scenario where an LWC component needs to apply a global utility CSS class (like a Salesforce Lightning Design System utility)?
Answer: Utility classes (e.g., slds-text-heading_large) are designed to penetrate the Shadow DOM. You simply apply the class directly to the element in the component's HTML template:<div class="slds-text-heading_large">Header</div>The LWC engine ensures that standard SLDS utility classes defined in the Light DOM are accessible within the Shadow DOM.
66. What is the significance of the this.template property in LWC, and why is it necessary for DOM manipulation?
Answer: this.template is a reference to the component's Shadow Root. It is the only entry point for safely querying and manipulating the component's private DOM elements. The use of this.template.querySelector('...') ensures that your queries are strictly limited to the component's encapsulated view, respecting Shadow DOM boundaries.
67. When using slots, if a parent component provides content that doesn't match any named slot, what happens to that content?
Answer: The content is automatically placed into the default slot (<slot></slot>) in the child component's template. If the child component does not define a default slot, the content is still passed to the child but is discarded (not rendered) by the browser's Shadow DOM mechanism.
68. What is the difference between a document.querySelector() call and a this.template.querySelector() call inside an LWC?
Answer:document.querySelector(): Queries the entire Light DOM (the main page content). It cannot see elements inside the Shadow DOM of the LWC component. This is generally discouraged due to security and encapsulation concerns.
this.template.querySelector(): Queries only the internal DOM elements within the LWC's Shadow Root. This is the correct and safe way to find elements within the component.
69. How would you conditionally style an LWC based on a value passed from the parent using the class attribute?
Answer: Use an ES6 Getter to construct the class string dynamically based on the component's reactive properties:
@api variant = 'default';get cardClasses() {let classes = 'slds-card'; if (this.variant === 'error'classes += ' error-border';}return classes;}
The template then binds to the getter: <div class={cardClasses}>...</div>.
70. What is the purpose of the lwc:if and lwc:else directives, and why are they wrapped in <template> tags?
Answer: These directives are LWC's mechanism for conditional rendering. They must be wrapped in <template> tags because the component's root (<c-my-component>) can only have one root element. The <template> tag itself is not rendered to the DOM; it is only a container for the LWC engine to execute the conditional logic before attaching the final markup to the Shadow Root.
71. How can you ensure that an external style sheet (CSS file) is applied only to a specific LWC, and not globally?
Answer: LWC automatically enforces this. When you create a CSS file (e.g., myComponent.css) in the same folder as the JS and HTML, the LWC engine automatically applies CSS scoping by adding unique attributes to the component's markup and transforming the CSS selectors. This ensures the styles are encapsulated within the component's Shadow DOM.
72. If a parent component wants to change the default styling of an SLDS base component (like lightning-button), what is the safest and most recommended approach?
Answer: Use the Custom CSS Properties (CSS Variables) approach provided by SLDS and LWC base components. Base components expose variables (e.g., --lwc-colorBackgroundButton) that the parent can override, providing a secure customization layer that respects encapsulation. Avoid deep selectors or Shadow Parts unless absolutely necessary.
73. What happens if you define a getter and a setter for the same property, but you don't use the @api decorator?
Answer: Without the @api decorator, the property is private.
The getter/setter pair will function like standard ES6 accessors.
Crucially: Changes made to this property by the parent will not be tracked, and the component will not re-render automatically unless the underlying private property being manipulated by the setter is itself a reactive field (i.e., decorated with @track or an initialized private field).
73.What is the is-initialized attribute used for in LWC base components (e.g., lightning-record-form)?
Answer: This is a boolean attribute that indicates when a component, particularly one that fetches data (like a form or data service component), has successfully completed its initial data loading and rendering. Developers can use this attribute or an equivalent getter/setter to ensure subsequent actions only run once the component is fully ready.
74. How do you handle conditional styling for an element based on an array value that is modified internally and is decorated with @track?
Answer:The array itself is declared with @track.Use a Getter that reads the array and returns a boolean or a class string based on the array's contents (e.g., get hasItems() { return this.trackedArray.length > 0; }).
Bind the result of the Getter to the template using the class attribute or if:true.
75. Explain the term "Host" in the context of Shadow DOM and LWC.
Answer: The "Host" is the actual LWC component element itself (e.g., the <c-my-component> tag) to which the Shadow DOM is attached. The styles applied directly to the LWC component's tag (e.g., <c-my-component class="external-style">) are applied to the Host. The Shadow DOM content is rendered inside the Host.
76. Why is using the imperative form of Apex calls often necessary, even though declarative @wire is generally preferred?
Answer: Imperative calls are necessary when
]Non-Cacheable Methods: The Apex method performs a DML operation, requires complex security checks, or is not idempotent, and thus cannot be annotated with @Cacheable=true.User Interaction: The method must be executed only in response to a user action (e.g., button click, form submission).
Conditional Chaining: The call depends on the result of a previous asynchronous operation (like a prior Apex call or LDS fetch).
77. When making an imperative Apex call, how do you handle security vulnerabilities related to the user's input?
Answer: All security validation, especially Field-Level Security and sanitization, must be enforced on the server-side, typically within the Apex controller. While LWC automatically adheres to the Locker Service for the client side, the server-side Apex must be secure, using techniques like with sharing (default) and standard Apex DML methods that respect user permissions.
78. How do you ensure proper cleanup of setTimeout and setInterval in an LWC component, and why is this a memory/performance concern?
Answer:Store the ID returned by the timer function: this.timerId = setTimeout(...).Clear the timer in the disconnectedCallback(): clearTimeout(this.timerId);.
Concern: If the timer is not cleared, the callback function continues to run even after the component is destroyed. Since the callback function is a closure, it maintains a reference to the component instance, preventing garbage collection and leading to a memory leak.
79. What is a "snapshot" in Jest testing for LWC, and when is it most effective?
Answer: A snapshot test captures a string representation of the rendered component's DOM structure at a specific point in time and compares it against a previously stored snapshot file.
Effectiveness: It is most effective for ensuring that the component's markup structure and flow have not unintentionally changed (e.g., making sure all slots are present, conditional rendering works, or specific CSS classes are applied).
80. When testing an LWC with Jest, how do you simulate an asynchronous event, such as an Apex method returning data via @wire?
Answer: You must use the Jest mocking framework to intercept the @wire service:
Mock: Use jest.mock on the imported Apex method.Resolve/Reject: Use the mock's exported utilities (getRecord.emit(...) for LDS or the specific Apex mock to control the data flow).
Flush Promises: Use return Promise.resolve().then(() => { /* assertions */ }); or await Promise.resolve(); to ensure the asynchronous promise chain finishes execution before assertions are run.
81. Why is it a best practice to keep LWC components shallow and stateless, relying on the container pattern?
Answer:
Shallow/Stateless (Presentational Components): These components receive data via @api properties and emit user actions via events. They have minimal internal state.Container Pattern: A higher-level component (the "Container") holds the state, performs all Apex/LDS calls, and manages complex logic.
Benefit: This separation maximizes reusability, improves performance (only the container component handles slow asynchronous calls), and makes testing simpler.
82How do you test a component's functionality that relies on the disconnectedCallback() hook in Jest?
Answer:
- Render the component and attach it to the testing DOM (document.body.appendChild(element);).Trigger the component's logic (e.g., start a timer).Manually remove the element from the DOM using element.remove(); or document.body.removeChild(element);.
- Verify that the cleanup action (e.g., the timer being cleared) was executed by checking if the corresponding mock was called.
83. What is the significance of the targetConfigs property in the component's .js-meta.xml file?
Answer: targetConfigs allows developers to define a custom configuration schema specific to a particular usage target (e.g., Record Page, App Page). It defines:- Which @api properties should be exposed as configurable fields in the Lightning App Builder.Conditional visibility rules for these fields.
- Default values for the configuration.
84. Describe the purpose of using JSON.parse(JSON.stringify(data)) when mutating data received from @wire, and what is the primary drawback of this approach?
Answer:- Purpose: This is a common shortcut used to create a deep clone of the data, breaking the read-only protection of the wired data. The deep clone allows mutation without violating the framework's contract.
- Drawback: This method is inefficient and unsafe for complex data. It fails to clone Date, Map, Set, and undefined values, and it doesn't handle circular references, making it unreliable for production code with complex data structures.
85. How can you ensure that a sensitive token or API key is not exposed in the client-side JavaScript of an LWC?
Answer: Sensitive information must never be hardcoded or stored in client-side LWC. All tokens and API calls involving secrets must be handled on the server side:- Use Apex to store and retrieve sensitive configuration.
- Use Named Credentials in Apex for authentication to external systems, ensuring the actual keys/tokens never leave the Salesforce server environment.
86. What is the primary role of the slotchange event in LWC?
Answer: The slotchange event fires on a child component's <slot> tag when content is dynamically added, removed, or changed inside that slot by the parent component. This allows the child to imperatively react to changes in the content that has been projected into it (e.g., recalculating a layout based on the number of projected elements).
87. How would you debug a failed refreshApex call, and what must be included in the argument?
Answer: A failed refreshApex call often happens when the argument passed is not the provisioned value object. - Debugging: The argument must be the variable that was initially wired (this.wiredResult). If refreshApex fails or doesn't execute, log this.wiredResult to confirm it is an object with data and error properties, and not undefined or the raw data itself.
88.When implementing a file upload feature, why must you use the lightning-file-upload component instead of attempting to handle the file imperatively in LWC?
Answer: lightning-file-upload is a highly secure, base component that handles the entire, complex file upload process for you, including:- Chunking the file into smaller parts.Handling the asynchronous transfer process.
- Creating the necessary ContentVersion and ContentDocumentLink records in Salesforce.
Attempting to replicate this imperatively in LWC is complex and inherently risky regarding security and data integrity.
89. Explain the benefits of using a dedicated LWC component for internationalization (i18n) strings rather than hardcoding labels.
Answer: Use Custom Labels imported via @salesforce/label. - Benefit: It allows the application to support multiple languages and translates all user-facing text automatically based on the user's language settings without any code changes or redeployment. Hardcoding strings prevents localization and requires manual updates for every language change.
90. How does the LWC runtime handle asynchronous JavaScript execution related to component rendering performance?
Answer: LWC uses an event-driven, asynchronous rendering queue. It batches all reactive changes (property updates, wire data) and performs a single, optimized DOM diffing operation. It minimizes direct DOM manipulation by developers and prioritizes a non-blocking UI. Heavy tasks are pushed to the end of the queue or offloaded to Apex/Web Workers.
91. In Jest, how do you mock a Lightning Message Service (LMS) publication and check if a sibling component correctly published a message?
Answer:- Import: Import the publish function from lightning/messageService.Mock: Use jest.mock('lightning/messageService') and include the mock implementation for publish.
- Assert: After triggering the action that should publish the message, assert the publish mock was called with the correct channel and payload: expect(publish).toHaveBeenCalledWith(mockContext, MY_CHANNEL, expectedPayload);
92. What is the getUniqueId() utility function, and when is it necessary for accessibility/form components?
Answer: getUniqueId() is a utility function used to generate a unique ID string. It is necessary when creating custom input elements to ensure they meet accessibility standards (WCAG). You need unique IDs to correctly link the <label> element's for attribute to the input element's id attribute for screen reader compatibility.
93. When working with date/time, why should the LWC component only store and display strings, and rely on the server (Apex) or LDS for date object manipulation?
Answer: JavaScript date objects are complex to manage, often leading to time zone and daylight savings issues. - Best Practice: The client-side should rely on ISO 8601 strings for storage and use the lightning-formatted-date-time base component to handle localization and display according to the user's locale and time zone settings, delegating complex calculations to the server.
94. How do you efficiently render a large array of records (e.g., 500 records) in an LWC list, considering performance constraints?
Answer: Virtualization is the only safe approach. - Implementation: Use a component that supports virtualization, like lightning-datatable (which handles it internally), or a custom solution that uses the Intersection Observer API to load only the records currently visible in the viewport, significantly reducing initial render time and memory usage.
95. Explain the purpose and function of the LWC compiler.
Answer: The LWC compiler is a build-time tool that runs before deployment. It performs several critical functions:
1. Validation: Checks component syntax and configuration (.js-meta.xml).
2. Transformation: Converts the LWC JavaScript (ES6+) into browser-compatible code (transpilation).
3. Wire/Apex Integration: Transforms @wire and Apex method imports into specific module loading calls.
4. Security Scoping: Applies CSS scoping rules and integrates Locker Service wrappers to enforce isolation and security.
The compiler ensures that the LWC adheres to web standards and Salesforce security policies before it ever reaches the runtime environment.
