Crack The Code - Top 100 LWC Interview Questions
Crack The Code - Top 100 LWC Interview Questions
What is SLDS?
SLDS is Salesforce Lightning Design System. The Developer Library and
Lightning Web Component are essential resources for those working on
code and design in the Salesforce platform.
💥Crack the Code: 100 Interview Questions on
Lightning Web Components!
in the below image greeting is the property which holds text sfdcamplified.
💥Crack the Code: 100 Interview Questions on
Lightning Web Components!
Output
💥Crack the Code: 100 Interview Questions on
Lightning Web Components!
HTML File
Eg - this.firstName = event.target.value
If property is inside the class, then use this. It specifies the current context.
targeted value
If you want to hide some of the components from the HTML and show it
for:each
Iterator
element on which we are doing iteration. Key gives unique id to each item.
💥Crack the Code: 100 Interview Questions on
Lightning Web Components!
Remember, without key we cannot do iteration.When a list changes, the
framework uses the key to rerender only the item that changed.
<template>
<template if:true={showTemplate1}>
<p>This is template 1</p>
</template>
<template if:true={showTemplate2}>
<p>This is template 2</p>
</template>
</template>
What is a decorator?
function.
• They are identified with the symbol ‘@’ as prefixed before a method
or a variable name.
There are some built-in decorators provided by LWC that we can use to
define properties and methods in components:
must declare a public API. There are two forms in the public API of a
component.
• public properties
• public methods
If you want to make the property to be called from another component, you
component. Along with decoration you have to import this in your js file
as:
re-rendered automatically.
parent component.
💥Crack the Code: 100 Interview Questions on
Lightning Web Components!
What are lifecycle hooks in Lightning Web Component?
Lightning web components have callback method, that are used to handle
lifecycle of the components. These are called lifecycle hooks. You can
Note: All lifecycle hooks are part of HTML custom element specification
• constructor()
• connectedCallback()
• rendered()
• renderedCallback()
• disconnectedCallback()
• errorCalllbback()
1.Constructor is called
💥Crack the Code: 100 Interview Questions on
Lightning Web Components!
6.Parent is rendered
11.Child is rendered
Let's use the Domino's Pizza website scenario to illustrate this in a more
relatable way:
Imagine you're visiting the Domino's Pizza website to order a pizza. The
process you go through on the website is like how components are
rendered in LWC. Here’s how it works:
This is like you deciding to order pizza from Domino's and opening their
website. The website's main page (parent) starts loading, and this is
analogous to the constructor method being called. The main page is setting
up resources, initializing state.
Now, the website asks for your location to deliver the pizza. This is like
setting a public property on the parent; the website can't proceed without
this info, much like a component might need input data to function properly.
With your location set, the website displays the Domino's branch closest to
you along with the menu. This stage is like the parent component being
inserted into the DOM; it's now part of the webpage and you can interact
with it.
As you browse the menu, the website might load special offers based on
your location or previous orders. This is like the connected callback; now
that the parent component is in the DOM, it can handle tasks like loading
data or setting up event listeners.
5. Parent is rendered:
You're now looking at the menu and deciding what pizza to order. The
parent component (the main page) is fully rendered and visible.
You decide on a pizza and click on it. This action loads a new component:
the pizza customization page. This is like the child component's constructor
being called; the child (pizza customization page) begins its initial setup.
- The customization page knows which pizza you selected and shows
you the correct toppings and price. This is like public property being set on
the child; it needs this data to display the correct information.
As you interact with the options, the page might display calorie counts or
update the price in real-time. This is like the child's connected callback; it
can now react to changes and update itself accordingly.
You finalize your pizza with your preferred toppings and it's now ready to
be added to the cart. This is like the child component being fully rendered.
After adding the pizza to your cart, maybe you decide to add a drink too.
The page updates the cart total. This is like the rendered callback; the
components have been rendered and now any post-render activities occur.
First, this happens in the child (updating the cart), then in the parent
(maybe updating the total items in the header's cart icon).
💥Crack the Code: 100 Interview Questions on
Lightning Web Components!
💥Crack the Code: 100 Interview Questions on
Lightning Web Components!
💥Crack the Code: 100 Interview Questions on
Lightning Web Components!
on. Your screen reflects these updates in real-time, getting you more
excited as the delivery time approaches. If there's a delay or a rush, the
tracker adjusts the progress display accordingly.
Explain constructor?
💥Crack the Code: 100 Interview Questions on
Lightning Web Components!
• Hook that fires when a component instance is created.
establishes the correct prototype chain and value for this. Always call
Do not assign any property in Constructor because they are not ready at
this point. The flow of Constructor is flows from parent to child. It means if
there are child components in LWC, then first parent constructor will be
constructor() {
super();
💥Crack the Code: 100 Interview Questions on
Lightning Web Components!
console.log('In Constructor');
}
What is connectedCallback?
won’t be yet.
• It can fire more than once. For example, if you remove an element
and then insert it into another position, such as when you reorder a
list, the hook fires several times. If you want code to run one time,
connectedCallback(){
console.log('In connectedCallback');
💥Crack the Code: 100 Interview Questions on
Lightning Web Components!
}
}
inserted yet.
app.html
<template>
<lightning-input label="Name" value={greeting}>
</lightning-input>
</template>
app.js
💥Crack the Code: 100 Interview Questions on
Lightning Web Components!
connectedCallback(){
console.log('connectedcallback');
this.greeting ='sfdcAmplified';
}
}
What is render?
HTML template.
render(){
console.log('In render');
💥Crack the Code: 100 Interview Questions on
Lightning Web Components!
}
}
service template.
• salesTemplate.html
• serviceTemplate.html
• salesTemplate.js
What is renderedCallback?
Note, You can set the properties in renderedCallback but best practice is
renderedCallback(){
console.log('In renderedCallback');
}
}
disconnectedCallback()
renderer file.
What is errorCallback?
💥Crack the Code: 100 Interview Questions on
Lightning Web Components!
Captures errors that may happen in all the descendant components
lifecycle hooks.
errorCallback(error, stack) {
alert(error);
}
the time of day, the website might show you different deals; for example, a
breakfast special if it's morning, a lunch deal around noon, and a dinner
What happens in LWC: Here’s where the lifecycle hook comes in. Before
the Domino’s website shows you any deals, it checks the time. Based on
see the most relevant offers when you're browsing, making your
Let’s say you're tracking your order on the Domino's website, but suddenly
there's a system glitch, and the tracker can't get your pizza's status.
Without proper handling, this could confuse you – you might wonder if your
crucial role. Instead of the tracker just freezing or showing a technical error
that might confuse you, the `errorCallback` function steps in. It catches this
experiencing a hiccup in our system, but don’t worry, your pizza is still on
its way!"
💥Crack the Code: 100 Interview Questions on
Lightning Web Components!
Difference between Render and rendered call back?
lifecycle have specific roles that help the tracker function properly and
Tracker," the `render` method controls what the user sees initially. This
could be the tracker interface with the different stages like 'Preparing,'
'Baking,' 'Quality Check,' 'Out for Delivery,' and 'Delivered,' but with
- In simpler terms, the `render` method sets up the stage, but the actors
from the kitchen about the pizza's status, the `renderedCallback` method
updates the UI to reflect this. So, when your pizza moves from 'Preparing'
to 'Baking,' this method is what updates the tracker on your screen, lighting
new scene begins (your order status updates), the stage manager ensures
the correct props are in place and the actors are ready (the tracker reflects
In summary, the `render` method sets up the "Pizza Tracker" display, while
reflects each update to your pizza's journey from the oven to your doorstep.
💥Crack the Code: 100 Interview Questions on
Lightning Web Components!
In Salesforce's Lightning Web Components (LWC), data from Salesforce is
often retrieved using either the `wire` service or imperative Apex. While
both approaches facilitate communication with the server and can call Apex
methods to retrieve data, they operate differently. Let's use the Domino's
Imagine the Domino's website has a feature where the menu updates
customer, just open the menu page, and it always shows the current
In LWC: This is similar to the `wire` service. When you "wire" a function or
property, Salesforce automatically listens for changes that affect the data
💥Crack the Code: 100 Interview Questions on
Lightning Web Components!
and retrieves fresh data when necessary. It's reactive; it updates the
@wire(getPizzas) pizzas;
Salesforce changes.
button. The menu only updates when you click this button. You have
In LWC: This is like using imperative Apex. You call Apex methods directly
at the specific times you decide, like in response to a user action (e.g.,
Differences:
Control: Imperative calls give you more control over error handling,
complex logic, and can be used for more than just fetching data (e.g.,
is better when you need more control over when and how data is fetched or
manipulated.
Events are actions that happen in the system we are programming — the
occurs.
For example, in an airport when the runway is clear for a plane to take off,
Data must be passed up using Events. Events are just standard JavaScript
events that we fire from the child component and listen into the parent.
can pass properties to the child via HTML attributes, or public methods.
have a relation?
DOM events.
Then, we can make an event target dispatch the created event invoking the
parent.js
travel through the DOM tree to arrive at its target and what happens to it
afterward
Example: We click a button; we not only click that button but you actually
clicking parent and its parent all the way to the body.
💥Crack the Code: 100 Interview Questions on
Lightning Web Components!
What is meaning of bubbles : false and composed : false (Default
behavior)?
• This is the default behavior, and bubbles and composed are not
• When this is in effect, the event would not bubble up the DOM, as
• We can listen these event only via defining the event handler to
In this behavior, the event bubbles up the DOM, but don’t cross the shadow
For example :- There are two component, where parent component contain
child component. If event is fired inside child component, the event only
💥Crack the Code: 100 Interview Questions on
Lightning Web Components!
bubbles up inside child component, and it would not cross it’s boundary,
In this case we will define listener and handler function in the JavaScript file
itself.
props);
💥Crack the Code: 100 Interview Questions on
Lightning Web Components!
Step 3: Attach Event Listener using addEventListener.
events. If you have other child components (not the one firing the event)
you can pass a property down to those children in response to the event.
💥Crack the Code: 100 Interview Questions on
Lightning Web Components!
For below three approaches we don’t need to write apex to do get data:
Note: Before you use an Apex method, make sure that there isn’t an easier
Syntax
Component
• Wire a property
• Wire a function
(change) data.
• If the cached data is stale, the framework retrieves the latest data
Scenario – Get the list of contact records from Salesforce using wire?
a list of contacts.
contactList.js
• The wire service either gets the list of contacts to the contacts.data
contactList.html
💥Crack the Code: 100 Interview Questions on
Lightning Web Components!
The template uses the if:true directive to check whether the
<template>
<lightning-card title="ApexWireMethodToProperty" icon-
name="custom:custom63">
<div class="slds-m-around_medium">
<template if:true={contacts.data}>
<template for:each={contacts.data} for:item="contact">
<p key={contact.Id}>{contact.Name}</p>
</template>
</template>
<template if:true={contacts.error}>
<c-error-panel errors={contacts.error}></c-error-panel>
</template>
</div>
</lightning-card>
</template>
Output
💥Crack the Code: 100 Interview Questions on
Lightning Web Components!
ContactMaster.apxc
apexWireMethodToProperty.
• The method must be static, and global or public. The method must be
contactDisplay.js
• The wire service gets the results to the wiredContacts() function via
rerenders.
contacts;
error;
@wire(getContactList)
wiredContacts({ error, data }) {
if (data) {
console.log('data: ', data);
this.contacts = data;
console.log('this.contacts: ', this.contacts);
this.error = undefined;
console.log('this.error: ', this.error);
} else if (error) {
console.log('error ', error);
this.error = error;
console.log('this.error: ', this.error);
this.contacts = undefined;
console.log('this.contacts : ', this.contacts);
}
}
}
contactDisplay.html
💥Crack the Code: 100 Interview Questions on
Lightning Web Components!
• The template uses the if:true directive to check for the
<template>
<lightning-card title="Apex Wire Method To Function" icon-
name="custom:custom63">
<div class="slds-m-around_medium">
<template if:true={contacts}>
<template for:each={contacts} for:item="contact">
<p key={contact.Id}>{contact.Name}</p>
</template>
</template>
<template if:true={error}>
<c-error-panel errors={error}></c-error-panel>
</template>
</div>
</lightning-card>
</template>
ContactMaster.apxc
@AuraEnabled(cacheable=true)
public static list<Contact> findContacts(String searchKey){
String key = '%' + searchKey + '%';
List<Contact> conlist = [SELECT Id,Name from Contact WHERE
Name LIKE :key LIMIT 10 ];
return conlist;
}
}
contactDisplay.html
💥Crack the Code: 100 Interview Questions on
Lightning Web Components!
The template uses “searchKey” as value in input field
<template>
<lightning-card
title="Apex Wire Method With Params"
>
<div class="slds-var-m-around_medium">
<lightning-input
type="search"
onchange={handleKeyChange}
class="slds-var-m-bottom_small"
label="Search"
value={searchKey}
></lightning-input>
<template if:true={contacts.data}>
<template for:each={contacts.data} for:item="contact">
<p key={contact.Id}>{contact.Name}</p>
</template>
</template>
<template if:true={contacts.error}>
<c-error-panel errors={contacts.error}></c-error-panel>
</template>
</div>
</lightning-card>
</template>
contactDisplay.js
💥Crack the Code: 100 Interview Questions on
Lightning Web Components!
• JavaScript shows the value of the searchkey parameter with $ to
searchKey = '';
handleKeyChange(event) {
const searchValue = event.target.value;
this.sexarchKey = searchValue;
}
}
💥Crack the Code: 100 Interview Questions on
Lightning Web Components!
How do you create a Lightning App that embeds an LWC
component?
<aura:application extends="force:slds">
<c:myLwcComponent />
</aura:application>
How do you use the Salesforce REST API in LWC? What are the best
practices for integrating with external systems?
To use the Salesforce REST API in LWC, we can use the built-in fetch
method or a third-party library like axios or jQuery.
Can you explain how to use the Lightning Message Service in LWC
and give an example?
connectedCallback() {
this.channel = createMessageChannel({
channelName: this.channelName,
isSubscribe: true
});
}
}
handleClick() {
const message = {
recordId: '001XXXXXXXXXXXXXXX'
};
publish(this.channel, message);
}
}
💥Crack the Code: 100 Interview Questions on
Lightning Web Components!
Subscribe to a message: Finally, to receive and act upon messages
published on a message channel, we can use the subscribe() method.
connectedCallback() {
this.channel = createMessageChannel({
channelName: this.channelName,
isSubscribe: true
});
this.subscription = subscribe(
this.channel,
message => {
console.log(message.recordId);
}
);
}
disconnectedCallback() {
unsubscribe(this.subscription);
}
}
• Declarative data binding: With the Lightning Data Service, you can
declaratively bind your component's UI elements to record data
without writing any Apex code or SOQL queries. This simplifies the
code and reduces the development time.
• Caching and automatic record updates: The Lightning Data
Service caches record data locally on the client side and
automatically updates it when changes occur in the database. This
improves performance and reduces the number of round trips to the
server.
• Automatic CRUD operations: The Lightning Data Service provides
a set of methods to create, read, update, and delete records. These
methods are automatically implemented and available for use in
your LWC component.
💥Crack the Code: 100 Interview Questions on
Lightning Web Components!
• Automatic sharing and field-level security: The Lightning Data
Service automatically enforces sharing rules and field-level
security when reading or modifying records.
What is the role of the Shadow DOM in LWC, and how does it differ
from the traditional DOM?
When we create an LWC component, its HTML template, and CSS styles
are automatically encapsulated in the Shadow DOM. The JavaScript
code can access the Shadow DOM via the “this.template” property,
but it cannot access the rest of the page's DOM directly.
@wire(getcoffee,{boatTypeId : ‘$coffeeTypeId})
True
What is LMS?
LMS is defined as the standard publish-subscribe library that enables
communication with DOM across the components be it Visualforce Pages,
Aura components, and Lightning Web Components (LWC) all can use it to
publish message and listen to messages published by others.
<template>
try {
} catch (error) {
</template>
You can use the fetch API to make HTTP callouts in LWC. Import the fetch
How can you make a Lightning Web Component available for use in
LWC?
You can use custom events and properties defined in a common parent
functions.
But If you need to track data changed from other places like Apex Trigger,
Flow, API integrations then we need to use the Change Data Capture
like below.
💥Crack the Code: 100 Interview Questions on
Lightning Web Components!
this.template.querySelector('[data-id]');
Also, we can query the component if we need to query the component with
this.template.querySelector(`[data-id='id-value']`);
You can also pass the string templates to the query selector function.
this.template.querySelector(`[data-id='${id}']`);
1// datatableExample.js
2import { LightningElement } from 'lwc';
3
4export default class DatatableExample extends LightningElement {
5 data = [
6 { Id: '001', Name: 'Account 1', Industry: 'Finance' },
7 { Id: '002', Name: 'Account 2', Industry: 'Technology' },
8 { Id: '003', Name: 'Account 3', Industry: 'Healthcare' },
9 ];
10
11 columns = [
12 { label: 'Account Name', fieldName: 'Name', type: 'text' },
13 { label: 'Industry', fieldName: 'Industry', type: 'text' },
14 ];
15}
Scenario: Suppose you have written a LWC which has the @wire
decorator to get the data from apex. But you are unable to get the
data from the server. What could be one of the reason?
Now, the `recordId` property will hold the record ID, and you can use it in
your component's logic as needed.
When you place this component on a record page and trigger it from a
Quick Action, it will automatically fetch and display the record ID of the
💥Crack the Code: 100 Interview Questions on
Lightning Web Components!
Yes
<lightning-output-field field-name="Name"></lightning-output-field>
</lightning-record-view-form>
In this example, FLS is enforced for the "Name" field of the "Account"
object, and if a user doesn't have permission to view the "Name" field, it
won't be displayed.
When writing Apex controllers that are called from your LWC, always check
FLS. Use the `SecurityEnforced` annotation.
@AuraEnabled(cacheable=true)
```
Utilize Schema methods in Apex to check if the current user has read,
create, or edit access to a field. This is more manual but allows for fine-
grained control.
return Schema.sObjectType.Account.fields.Name.isAccessible();
Here, `isAccessible()` checks if the current user has read access to the
Account's Name field.