LWC Questions and Answers 1743773761
LWC Questions and Answers 1743773761
mastering Lightning
Web Components (LWC)
Salesiorce interviews!
LI Understand core concepts
LI Tackle real-world scenarios
LI Enhance your LWC expertise
Question 1 - What is the structure of LWC?
Answer:LWC is built using these main parts, including HTML, JS, CSS and XML.
Question 2 - Can you explain the purpose of each part of the LWC folder structure?
Answer:
Question 3 -What is the recommended naming convention that should be followed while
working with LWC?
Answer: The following are the rules that we should follow while naming our LWC:
1. The component must start with the lowercase i.e. it should follow camel case.
2. It must contain only alphanumeric or underscore characters, not a dash.
3. While referencing components in HTML we should use the kebab case.
4. Must contain only alphanumeric or underscore characters
Below are the samples of the camel case and kebab case
CamelCase:
myVariableName, fetchDataFromServer
Kebab-case:
my-variable-name, fetch-data-from-server
Question 4 - What is SLDS?
Answer: SLDS, or Salesforce Lightning Design System, is a key framework for designing and building
consistent user interfaces on the Salesforce platform.
Question 5 - What are the advantages of LWC over Aura components?
Answer:
• Standard events are built-in browser events like click or change, which handle common interactions.
• Custom events are ones you define and dispatch yourself, making them ideal for more complex
communication, such as passing data between components or triggering specific actions.
Answer: Here we have to establish the Parent-Child Communication. It will be done through @api
decorator. Let's look at the below example.
We have created two components here childComp and parentComp. We have messageFromParent in
childComp which is receiving the value from Parent.
childComp.js
childComp.html
childComp.js-meta.xml
1l version="1.0 ?>11
xmlns="http://soap.sforce.com/2006/04/metadata"
57.0
true
lightning_AppPage
parentComp.js
import { LightningElement} from 'lwc';
export default class ParentComp extends LightningElement
{ message= ''
handleChange(event) {
this.message= event.detail.value
}
}
parentComp.html
type= text"
11
variant= standard
11 11
name= Message"
11
label="Message"
placeholder="type here... 11
value= {message}
onchange={handleChange}
message-from-parent= {message}
parentComp.js-meta.xml
xmlns= http://soap.sforce.com/2006/04/metadata
11
57.0
true
lightning_AppPage
Output
m Working wi h Da a
Parent Component
Child Component
Question 12 - Referring to the above scenario if I want to communicate Child to Parent where
CompA is the parent and CompB is the child. How can we send data from CompB to CompA?
Answer: Here we have to show Child to Parent Communication. It will be done through the dispatching of
the custom event from the child and then the parent component will receive it. Here we have two
components childComp and parentComp. In the Child component, we have an input box to enter our value
and then on clicking of Send Message button, we will dispatch our event.
In Parent component markup, where we defined our child, to catch the event we have to use "on" as a
prefix just like we do in the standard events like onclick, and onchange. After that, to handle the event we
have a handler in the JS handleMessageFromChild which is receiving the event and in the detail, we have
our value. Below is a sample of Child to Child-to Parent communication.
childComp.js
childComp.html
<template>
<lightning-card variant=11Narrow11 title=11Child Component11>
<lightning-input type=11text11 variant=11standard11 name="Message11
label=11Message11 placeholder="type here...11
value={messageFromChild} onchange={handleChange}></lightning-
input>
<lightning-button label=11Send Message11 title=11Send Message11
onclick={handleClick}></lightning-button>
</lightning-card>
</template>
childComp.js-meta.xml
<?xml version=111.011?>
<LightningComponentBundle
xmlns=11http://soap.sforce.com/2006/04/metadata11>
<apiVersion>57.0</apiVersion>
<isExposed>true</isExposed>
<targets>
<target>lightning_AppPage</target>
</targets>
</LightningComponentBundle>
parentComp.js
parentComp.html
<template>
<lightning-card variant="Narrow" title="Parent Component">
<div>Message from child is : {messageRecieved} </div>
</lightning-card>
<c-child-comp message-from-child={messageRecieved} onsend =
{handleMessageFromChild}></c-child-comp>
</template>
parentComp.js-meta.xml
<LightningComponentBundle
xmIns= http://soap.sforce.com/2006/04/metadata >
11 11
<apiVersion>57.0</apiVersion>
<isExposed>true</isExposed>
<targets>
<target>lightning_AppPage</target>
</targets>
</LightningComponentBundle>
Output
Parent Component
Message from child is : No Message
Child Component
Message
type here...
Send Message J
• ... Sales Home Opportunities V Leads V Tasks V
r Parent Component
Message from child is: Hey!! From Child
Child Component
Message
Send Message I
-
You can @wire a property or a function to receive the data from Apex. You have to annotate your apex
method with@AuraEnabled(cacheable=true). By using the wire services it reduces the server call because
it loads the data from the cache. We can't do DML with a wire decorator.
Imperative Call
If we want to invoke our method call on some click or to control our method invocation we have to call
the method imperatively. Calling our method in this way is also helpful if we want to perform some DML
operations. Here, we don't annotate our method (cacheable=true).
Here we have the getAccount method that we imported from our Apex controller and returned account
data where ID matches to accld. While using wire, to make the variable reactive and receive ID from the
record page, we can annotate it with @api and display it with a $ sign.
However, in the imperative call, it is different, we use it with this.accld and in imperative it will return the
promise. Where .then is the resolve and .catch is the reject.
fl wire call
@wire(getAccount,{ accld: '$accld' })
wiredAccResult({ data, error}) {
if (data) {
console.log('data coming for accounts are ', data)
console.log('length of data coming for accounts are', data.length)
}
if (error) {
console.log('Error in fetching account ',
JSON.stringify(error.message));
}
}
// Imperative call
fetchAccount (){
getAccount({ accld: this.accld})
.then(data=>{
f/console.log('length of data coming for accounts are ',data.length)
})
.catch(error=>{
console.log('Error occurred while fetching account
',error.body.message)
})
}
Answer: The lifecycle hooks in LWC provide the ability to control your code at various stages. We have
different types of lifecycle hooks in LWC which run in a specific order:
1. constructor()
2. ConnectedCallback()
3. RenderedCallback()
4. DisconnectedCallback()
5. ErrorCallback()
Note: If we also have the child component, Child flow will run after the connectedCallback and before the
renderedCallback in the same order.
Answer: Conditional rendering in Salesforce helps to show content based on specific conditions. We can
achieve this by template if:true or with new lwc:if, lwc:elseif, and lwc:else.
Question 17 - What is the difference between for:each and the map in LWC?
Answer: For:each and Map both are used to handle Arrays. But the major difference between them is that
we can update the element in for:each while iterating but it doesn't return the new array. However, Map
returns the new array with the modified elements.
As we see in the event bubbling event is moving from bottom to top. The same in event capturing event is
moving from top to bottom.
Question 20 - Suppose I have two independent components CompA and CompB. How can I
establish communication between them?
Answer: It shows communication between unrelated components so here we will establish communication
via Lightning Message Service.
In this case, we will have to create a message channel, a publisher component from which we have to send
the data and a subscriber component from which we have to receive the data.
Are you preparing for the Salesforce Certifications? Check out the Salesforce certification practice set_bere
contactCreator.js
contactCreator.html
ob1cct-Jp1-nJmc={objectApiName} f1clds={fields}
onsucccss={handleSuccess}
contactCreator..js-meta.xml
lightning_AppPage
lightning_HomePage
Here Cancel and Save buttons will come automatically with the record form and clicking on Save button it
fire the onsuccess event. If we want to perform some additional things we can handle that.
OUTPUT
Ema,I I
I I
F,rstName
I
'last Name
I Cancel )I'll
m Working with Da a
0 Contxt created
Record 10: 00lJ100000lOwULAJC
(8)
Emol
abc: tf'St.(Offi
Question 23 - Suppose I have one LWC component in which I have a property name
"message". I want this message value to be dynamic like I want to display different values on
each page. How can I achieve it?
Answer: To achieve this scenario we have to utilize the meta xml file. There we have to define our target
config and the property name, with its type, default value and label. Below is the sample code and output.
We have created a helloWorld LWC component to demonstrate this. When we deploy this component we
will have the option to provide the custom message.
helloWorld.html
class= slds-m-around_medium
11 11
Hello, {greeting}!
helloWorld.js
import { LightningElement, api} from 'lwc';
export default class HelloWorld extends LightningElement
{ @api greeting;
}
helloWorld.js-meta.xml
<LightningComponentBundle
xmlns= http://soap.sforce.com/2006/04/metadata
11 11
<apiVersion>52.0</apiVersion>
<isExposed>true</isExposed>
<targets>
<target>lightning_AppPage</target>
<target>lightning_RecordPage</target>
<target>lightning_HomePage</target>
</targets>
<targetConfigs>
<targetConfig
targets="lightning_HomePage,lightning_AppPage,lightning_Rec
ordPage > 11
Salesforce"
label=" Enter the message" />
</targetConfig>
</targetConfigs>
</LightningComponentBundle>
OUTPUT
0-
•·
u
a
aa...o<..-:..U<1
a
a-
a--=-
a.-
a-
a
a--· -
a-,;r...,,....
a-----
,0::::_ MUI
•·
;: : ; : ' - ==-=·
- -
11 " " '• . . , .
y-. ........
a (---] i:---l V Sol , V,s,t,.Lty
a-•--·-
a .. +
a--,.;;,
a
a.-
a
a
a--,t""'
a - , g l ..,,_
a--""-
a- ..,....
a--,N,-
),ld
a--""
Question 24 - Suppose I have two LWC components parentComp and childComp. How can I
access childComp's function in the parentComp's JS?
Answer: Here in the child component we have to annotate our method [email protected] suppose I have method
in child component handleData
child component
parent component
handleChange(){
this.template.querySelector(1c-child-comp1).handleData();
Answer: Lightning Message Service is used to communicate across different components like between
unrelated components, Aura, and VisualForce.
Answer: Lightning Data Service (LDS) is a robust feature in Salesforce that enables Lightning Web
Components (LWC) to seamlessly interact with Salesforce data, eliminating the need for Apex code.
Functioning on the client side, LDS simplifies data retrieval and management in LWCs, providing key
features that enhance the efficiency and ease of working with Salesforce data.
Question 27 - What is the difference between async and await in JS?
Answer: It is a way to write an asynchronous code. Async is a keyword used to define an asynchronous
function which returns a promise and await is used to pause that execution until the async returns the
promise whether resolved or rejected.
Answer: uiRecordApi is the module in LWC that provides us with various methods to create, update, and
delete records.
• createRecord(recordlnput)
• createRecordlnputFilteredByEditedFields(recordlnput, originalRecord)
• deleteRecord(recordld)
• generateRecordlnputForCreate(record, objectlnfo)
• generateRecordlnputForUpdate(record, objectlnfo)
• getFieldValue(record, field)
• getFieldDisplayValue(record, field)
Answer: Promise.all take multiple promises and return the promises when all get fulfilled and will reject
immediately upon any of the input promises rejected.
Promise.race also takes multiple promises but it returns a single promise whichever settles first or we can
say whichever resolves first unlike promise.all.
Question 33 - What are deep copy and shallow copy of objects?
Answer: Shallow copy creates the copy of an object but not for its nested properties. It creates a reference
to it. So any changes to the nested properties of a copied object will also change to the original one. Like
spread operator creates the shallow copy.
But for a deep copy, it is different, it creates the copy without actually referencing them so any changes in
the copied object will not affect the original one and by JSON.stringify(JSON.parse(objl)) we can create
the deep copy of objects.
Answer: Reduce function iterates on the array's every element and accumulates them into a single value.
Below is an example. Here index is basically we can say the collector, currentltem is the current value of
the array that is being iterated and O is the starting point.
So when it starts to iterate It goes like 0+1 (0 goes into the index as first time and currentltem is the 1) ->
1+2 ( now the index value will be 1 and currentltem is 2) it goes on like that.
> arr = (1,2,3, ]
arr.reduce((index,currentitem) =>index+ currentitem,0);
<- 10
> I
Slower due to the heavy framework Faster with lightweight and native
overhead. browser support.
Relies on polyfills and Salesforce Built for modern browsers with minimal
infrastructure. polyfills.
o Data flows in a single direction, from the JavaScript controller to the HTML template.
o This approach ensures better control over data and prevents unintended modifications, as the UI
cannot directly update the data in the controller.
o Commonly used for displaying read-only data or passing data to child components.
o Typically achieved using directives like @track or specific event handlers for input fields.
0
This approach is useful for interactive components where user input needs to update the
underlying data.
Are you preparing for the Salesforce Certifications? Check out the Salesforce certification practice set
logProperty() {
console.log(this.myProperty); // Outputs: Hello, LWC!
}
}
Answer: The lightning-record-form component is used to quickly create forms for adding, viewing, or
updating records. It leverages Lightning Data Service, so no additional Apex controllers are needed for
creating or editing record data.
Additionally, it handles field-level security and sharing, ensuring that users only see the data they have
access to.
Answer: Conditional rendering in Lightning Web Components (LWC) lets you dynamically manage what
appears on the user interface based on specific conditions. By using directives like if:true and if:false in the
HTML template, you can control the visibility of elements depending on the value of a JavaScript
property defined in the component's class.
Example:
<template>
<button onclick={toggleVisibility}>Toggle Visibility</button>
<template if:true={isVisible}>
<p>This text appears when isVisible is true.</p>
</template>
</template>
toggleVisibility(){
this.isVisible = !this.isVisible;
}
}
Answer: connectedCallback() is a lifecycle hook in Lightning Web Components (LWC) that gets executed
when a component is inserted into the DOM. It flows from parent to child.
Question 46 - What is renderedCallback() in LWC?
Answer: The renderedCallback() lifecycle hook in Lightning Web Components (LWC) is triggered after the
component's template and all its child components are fully rendered in the DOM. This execution follows
a flow from child components to the parent component.
Answer: In Lightning Web Components (LWC), the disconnectedCallback() is a lifecycle hook that gets
triggered when a component is removed from the DOM.
Question 48 - What is event propagation in Salesforce?
Answer: Event propagation in Salesforce is all about how events move from one component to another,
especially in Lightning Web Components (LWC). It's like a chain reaction where an event from a child
component can pass through the parent components, or the other way around, depending on how the
event is set up.
Answer: Serialization in LWC is the process of converting objects into a string format (usually JSON) for
easier storage, transmission, or communication between components and systems.
Answer: The getRelatedListCount function in Lightning Web Components (LWC) is a part of Lightning
Data Service, and it helps retrieve the count of records in a related list for a specific parent record. This
method enables you to efficiently get the number of related records (such as Contacts related to an
Account) without the need to fetch the complete set of related records.
Are you preparing for the Salesforce Certifications? Check out the Salesforce certification practice set here
Answer: No, you cannot directly use @wire inside the connectedCallback() function in Lightning Web
Components (LWC).
Question 52 - What is JSON.stringify used for in LWC?
Answer: In Lightning Web Components (LWC), the JSON.stringify() method is used to transform a
JavaScript object or value into a JSON string. This comes in handy when you need to work with data in a
text format whether it's for sending it to an external system, displaying it on the user interface, or just for
debugging purposes.
Question 53 - How can I get the current user's ID in LWC without Apex?
Answer: Yes, we can retrieve the current user ID without using Apex by simply importing -
To use the navigation services, we need to import the NavigationMixin from the lightning/navigation
module. This allows us to navigate to various destinations, such as list views, object pages, record pages, or
even open files, all within our LWC components.
Syntax -