0% found this document useful (0 votes)
12 views

61 LWC Lightning Web Component Interview Questions and Answers

The document provides a comprehensive guide of 61 scenario-based interview questions and answers specifically for Salesforce Lightning Web Components (LWC). It covers essential topics such as wire functions, lifecycle hooks, event handling, and data communication between components, aimed at helping candidates prepare effectively for LWC interviews. The content is crafted by industry professionals to enhance the interview readiness of aspiring Salesforce developers.

Uploaded by

layavardhansadda
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

61 LWC Lightning Web Component Interview Questions and Answers

The document provides a comprehensive guide of 61 scenario-based interview questions and answers specifically for Salesforce Lightning Web Components (LWC). It covers essential topics such as wire functions, lifecycle hooks, event handling, and data communication between components, aimed at helping candidates prepare effectively for LWC interviews. The content is crafted by industry professionals to enhance the interview readiness of aspiring Salesforce developers.

Uploaded by

layavardhansadda
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 25

05/06/2024, 16:32 61 LWC Lightning Web Component Interview Questions and Answers

Home About Us Courses Registration Interview Questions Tutorials Reviews

Contact Us

61 LWC Lightning Web Component Interview


Questions and Answers

Lightning Web Component Interview Questions with answers

61 Scenario based Salesforce LWC Lightning Web


Components interview questions with detailed answers
Prepare for your Salesforce LWC Lightning Web Components interviews with our
comprehensive guide of 61 scenario-based questions and detailed answers. Crafted by
industry professionals with real-world experience, these questions cover crucial aspects
you need to master. By studying these answers, you can confidently approach any
interview and increase your chances of success significantly. We guarantee that thorough
preparation with these resources will help you pass any Salesforce LWC interview with
flying colors.

Table of Contents

wire function
Whatsapp Chat
Lifecycle hooks
Call us on:  IN +91 93478 54179 , 93467 64857 , USA +1 (415) 529-7271 || Request Call Back || Please call to USA number during USA day time.

https://www.crsinfosolutions.com/61-lwc-lightning-web-component-interview-questions/ 1/27
05/06/2024, 16:32 61 LWC Lightning Web Component Interview Questions and Answers

event.StopPropogation() Vs Event.preventDefault()?
Promise in async transactions?
What are web components, Is LWC based on web components?

What does composed = true does in an event?


What are callback functions in LWC?

Callback hell?
Can I deploy component with empty css file?
What is difference between var and let in JS?

Do we have application events in LWC?


What is difference between ‘==’ and ‘===’?

What is String interpolation?

What are template literals?


Why do we put constants outside of class in LWC?

What is reduce method in JS?

How can you pass data between LWC components?


How can you communicate from child to parent component in LWC?

How do you handle asynchronous operations in LWC?

How can you conditionally render elements in LWC?

Scenario based

For Beginners
For Experienced

Interview Questions For Beginners


1. Can we call the @AuraEnabled function in the apex class
using wire ?

Ans: Function also needs to have cacheable = true annotation ie should be like
@AuraEnabled(cacheable = true)
Whatsapp Chat

2.CallWhat do you mean by cacheable = true annotations ?


us on:  IN +91 93478 54179 , 93467 64857 , USA +1 (415) 529-7271 || Request Call Back || Please call to USA number during USA day time.

https://www.crsinfosolutions.com/61-lwc-lightning-web-component-interview-questions/ 2/27
05/06/2024, 16:32 61 LWC Lightning Web Component Interview Questions and Answers

Ans: First of all when you mark function as cacheable = true it can only retrieve data i.e. it
cant have any DML.
It is used to improve component performance by quickly showing cached data from client
side storage without waiting for server trip.
Remember to refresh the stale data provisioned by Apex we have to use refreshApex as
LDS doesn’t manage data coming from Apex ( In case of wired service)
Read more: Salesforce Admin Tutorial

3. Will the below code deploy? (Assuming all variables and apex
class function exists).

@wire(getBoats,{
boatTypeId : this.boatTypeId
})
getBoats(error,data){
}

Ans: No it wont when passing a variable in wire you should always use $ along with
variable, it should be written like
@wire(getBoats,{boatTypeId : ‘$boatTypeId})

4. Why do we use $ when passing property in wire function, what


does it mean? [Latest Salesforce lightning interview questions
and answers]

Ans: $ prefix tells the wire service to treat values passed as a property of the class and
evaluate it as this.propertyName and the property is reactive. If the property’s value
changes, new data is provisioned and the component renders.

Join our Salesforce online course for comprehensive, hands-on training with real-time
projects. Benefit from expert guidance, daily notes, and interview preparation to excel in
your Salesforce career.

See the below code and answer the following question: [Scenario based Salesforce
Lightning Interview question with relevant answer]

5. If I want to refresh the wired data in the above function, can I


Whatsapp Chat
call refreshApex(this.someVar) ?
Call us on:  IN +91 93478 54179 , 93467 64857 , USA +1 (415) 529-7271 || Request Call Back || Please call to USA number during USA day time.

https://www.crsinfosolutions.com/61-lwc-lightning-web-component-interview-questions/ 3/27
05/06/2024, 16:32 61 LWC Lightning Web Component Interview Questions and Answers

@wire(getBoats,{boatTypeId : ‘$boatTypeId’})
getBoats({error,data}){
if(data){
this.someVar = data;
this.error = undefined;
}
else if(error){
this.error = error;
this.someVar = undefined ;
}
}

Ans:

No we cant call refreshApex(this.someVar) rather refreshApex is called on whole result


provisioned from the wire service not just the data part, we will have to rewrite it as below
:

@wire(getBoats,{boatTypeId : ‘$boatTypeId’})
getBoats(result){
this.mainResult = result;
if(result.data){
this.someVar = result.data;
this.error = undefined;
}
else if(result.error){
this.error = result.error;
this.someVar = undefined ;
}
}

Now we can refresh data as refreshApex(this.mainResult).

6. Can we call a wire function inside a javascript function like


below :

searchBoats(event){
@wire(getBoats,{
boatTypeId: ‘$boatTypeId’
}
getBoats(data,error){
} Whatsapp Chat
}

Call us on:  IN +91 93478 54179 , 93467 64857 , USA +1 (415) 529-7271 || Request Call Back || Please call to USA number during USA day time.

https://www.crsinfosolutions.com/61-lwc-lightning-web-component-interview-questions/ 4/27
05/06/2024, 16:32 61 LWC Lightning Web Component Interview Questions and Answers

Assume searchBoats is being called on click of button? Will I be able to deploy the
code ?

Ans: No you cant call it like this , code will not deploy. You will receive error as leading
decorators must be attached to class which means decorators like wire can be directly
under class only not inside any other function.

Similarly if you try to define variable with @track or api decorator inside a function it will
fail.

Join 100% hands-on career building Salesforce online training. Enroll today for free
demo!

7. When is the wire method/property called in the lifecycle of a


component ?

Ans: Wired service is called right after component is created ie after constructor and is
again called when parameter that you are passing is made available.

8. What are lifecycle hooks in LWC?

Ans: A lifecycle hook is a callback method triggered at a specific phase of a component


instance’s lifecycle.

There are following hooks supported in LWC :

Constructor : Called when the component is created.

Connectedcallback : Called when the element is inserted into a document. This hook
flows from parent to child.

RenderedCallback : Called after every render of the component. This lifecycle hook is
specific to Lightning Web Components, it isn’t from the HTML custom elements
specification. This hook flows from child to parent. Ie its not part of HTMLElement rather
defined in LightningElement.

Disconnectedcallback : Called when the element is removed from a document. This


hook flows from parent to child. Whatsapp Chat

Call us on:  IN +91 93478 54179 , 93467 64857 , USA +1 (415) 529-7271 || Request Call Back || Please call to USA number during USA day time.

https://www.crsinfosolutions.com/61-lwc-lightning-web-component-interview-questions/ 5/27
05/06/2024, 16:32 61 LWC Lightning Web Component Interview Questions and Answers

Errorcallback: Called when a descendant component throws an error. The error


argument is a JavaScript native error object, and the stack argument is a string. This
lifecycle hook is specific to Lightning Web Components, it isn’t from the HTML custom
elements specification.

9. Is wire method called multiple times during lifecycle of


component ? (True / False)

Ans: True

10. What is the difference in below two codes , will they both
compile ? Give same results ?

Code 1 :
@wire(getBoats)
getBoats({data,error}){
if(data)
console.log(‘print here’);
Else if(error)
console.log(‘print in else’);
}
@wire(getBoats,{})
getBoats({error,data}){
if(data)
console.log(‘print here’);
Else if(error)
console.log(‘print in else’);
}

Ans: Both will compile they are same.

50 LWC Lightning Web Component Interview Questions


Part 1
11. Is it mandatory to use data, error only in wired method, can I
use some other variable like below : Scenario based interview
question with answers

@wire(getBoats)
getBoats({myData,myError}){
if(mydata)
console.log(‘i am in data’); Whatsapp Chat
else if(myError)
Call us on:console.log(‘I
 IN +91 93478 54179 am in 64857
, 93467 error’);
, USA +1 (415) 529-7271 || Request Call Back || Please call to USA number during USA day time.

https://www.crsinfosolutions.com/61-lwc-lightning-web-component-interview-questions/ 6/27
05/06/2024, 16:32 61 LWC Lightning Web Component Interview Questions and Answers

}
Will the code deploy successfully or I will receive an error ?

Ans: We cant use any other variable name other than data, error they are hardcoded in
wire service. Code will successfully deploy but wire service wont be able to fetch any data.

Salesforce Lightning LWC interview questions and answers

12. What is the difference between event.StopPropogation() and


Event.preventDefault()?

Ans: stopPropagation prevents further propagation of the current event in the capturing
and bubbling phases. preventDefault prevents the default action the browser makes on
that event.

10.

13. If we add required attribute in lightning-input , will I get an


error on leaving the field empty ?

Ans: No unless you also add logic in backend javascript file to actually throw an error
using checkValidity and reportValidity.
Whatsapp Chat
14. Are quick actions supported for LWC components ?
Call us on:  IN +91 93478 54179 , 93467 64857 , USA +1 (415) 529-7271 || Request Call Back || Please call to USA number during USA day time.

https://www.crsinfosolutions.com/61-lwc-lightning-web-component-interview-questions/ 7/27
05/06/2024, 16:32 61 LWC Lightning Web Component Interview Questions and Answers

Ans: Quick actions are supported by LWC in Summer 21 or later orgs. LWC quick actions
are only supported on record pages.
Learn Salesforce programming with Step-by-Step Salesforce Apex Developer Tutorial
for beginners lessons.

15. How can i reference record ID of page in my component


which is fired from quick action.

Ans: There are two types of quick actions in LWC :


Screen actions : Normal action which open a modal
Headless actions : Which dont have any html file rather just logic written in js ie no modal
window will come up
In case of screen actions we will be able to get recordID by just defining recordID as
public property in the component.
For headless action you have to define @api invoke method which is auto called and
recordID will be set after this function is called.

Join 100% hands-on career building Salesforce online training. Enroll today for free
demo!

16. What is a promise in async transactions? What are it different


stages. [Latest Salesforce lightning interview questions and
answers]

Ans:
Promise is object returned in async transaction which notifies you about completion or
failure of transaction.
For example when you call apex imperatively it returns you a promise object on the basis
of object returned execution either goes into (then) ie transaction was successful or
(catch) which means transaction failed.

Stages of promises are :

Pending: Waiting for result.


Fulfilled: Promise results in success.
Rejected: Promise result in failure. Whatsapp Chat

17. What is the difference between Promise and Promise.all?


Call us on:  IN +91 93478 54179 , 93467 64857 , USA +1 (415) 529-7271 || Request Call Back || Please call to USA number during USA day time.

https://www.crsinfosolutions.com/61-lwc-lightning-web-component-interview-questions/ 8/27
05/06/2024, 16:32 61 LWC Lightning Web Component Interview Questions and Answers

Promise.All takes in multiple promises in it and returns a single promise object.


Promise.all is used when I want to make sure once all promises are resolved then only
execute then block.

18. What are web components, Is LWC based on web


components?

Ans: In simplest language , web components can be explained as it allows you to create
and re-use custom components as html tags in a component with their functionality
encapsulated from rest of your code.
Web components has 4 pillars which make it so amazing.
HTML Template : user defined templates which are rendered until called upon.
Custom Elements : With this we can embed as components merely as html tags in our
template.
Shadow DOM : With this we can separate DOM of each custom element from each other
to make sure nothing from any components leaks into each other.
HTML Imports : You can import other html documents in another html document for
example we can import multiple templates into one component then use render function to
display a template.
Yes LWC is based on web components
If you look at LWC architecture Salesforce only adds security , LDS and base components
rest is based on web components and es 7.

19. Why do we extend LightningElement?

Ans: LightningElement is custom wrapper on HTMLElement which actually contains all the
lifecycle hooks methods over which Salesforce did some customization.

20. When we create new component why does it say export


default ComponentName ?

Ans: Because of export default component only we are able to embed one component into
another.

Part – 2 | 50 LWC Lightning Web Component Interview


Questions
Whatsapp Chat
21. How do I retrieve elements on the basis of ID?
Call us on:  IN +91 93478 54179 , 93467 64857 , USA +1 (415) 529-7271 || Request Call Back || Please call to USA number during USA day time.

https://www.crsinfosolutions.com/61-lwc-lightning-web-component-interview-questions/ 9/27
05/06/2024, 16:32 61 LWC Lightning Web Component Interview Questions and Answers

Ans: We should never use “id” in lwc as id that you will define in LWC may get
transformed into something entirely different on rendering, rather use data-id in your tags
to reference them.

22. How to send data from Parent to Child in LWC?

Ans: For parent to child communication you just need to expose your function or attribute
as @api then in your parent component you can use querySelector to actually query the
child component access exposed attribute or method.

23. If we parent component A and there are two component B and


C as child components. How can we communicate between B and
C?

Ans: We should fire up event from child component B to parent A then from A call attribute
/ function exposed (as @api) and pass data into C component.

24. What does composed = true does in an event ?

Ans: These type of events can bubble up inside dom and also able to cross shadow
boundary.

26. When you fire an event, can i capture it in same template/


component ?

Ans: No

27. Is bubble : false and composed : true possible in an event ?

Ans: No

28. What is the difference between below :

a. Bubble : false and composed : false


b. Bubble : true and composed : true
c. Bubble : true and composed : false

29. What are callback functions in LWC ?

Whatsapp
Ans: Callback functions are nothing but functions passed as parameter into other Chat
functions.
Call us on:  IN +91 93478 54179 , 93467 64857 , USA +1 (415) 529-7271 || Request Call Back || Please call to USA number during USA day time.

https://www.crsinfosolutions.com/61-lwc-lightning-web-component-interview-questions/ 10/27
05/06/2024, 16:32 61 LWC Lightning Web Component Interview Questions and Answers

30. Are callback functions synchronous or asynchronous ?

Ans: Functions are neither async or sync in themselves rather depend on where are they
being passed for example if a function in passed into reduce method is sync but if function
is being passed into setTimeout function its async.

Learn Salesforce programming with Step-by-Step Salesforce Apex Developer Tutorial


for beginners lessons.

31. What is callback hell?

Ans: In most simple words callback hell occurs when there are many functions you want
to call async and you end up puting them one side each another and as the code grows it
becomes very difficult to read for example :

getData(function(x) {
getMoreData(x, function(y) {
getMoreData(y, function(z) { ... });
});
});

50 LWC Lightning Web Component Interview Questions


Part 1
32. What are decorators in LWC (Lightning web components) in
Salesforce? Latest interview question.

Ans: The Lightning Web Components programming model has three decorators that add
functionality to a property or function. There are 3 decorators for LWC
@track , @wire, @api

33. When do I use @track on a property ? Do I still need it


considering all properties are by default reactive now?

Ans: After Spring 20 all the properties are made by default reactive ie we dont need
@track for primitive properties. We still need it for array or object type properties

34. Can I use multiple decorators on one property ?


Whatsapp Chat
Ans: No we cant use multiple decorators on same property.
Call us on:  IN +91 93478 54179 , 93467 64857 , USA +1 (415) 529-7271 || Request Call Back || Please call to USA number during USA day time.

https://www.crsinfosolutions.com/61-lwc-lightning-web-component-interview-questions/ 11/27
05/06/2024, 16:32 61 LWC Lightning Web Component Interview Questions and Answers

35. Can I deploy component with empty css file ?

Ans: No we cant do that

36. What is difference between var and let in JS ?

Ans: In simple words difference is var is function scoped while let is block scoped
Var allows you to redeclare same variable while let will throw an error
Var variables are hoisted that is you can access them even before they are declared in
code its just they will return undefined value while with let it will throw an error.

37. Is there any difference in how we add LWC component inside


another LWC component and inside AURA component ?

Ans: Difference is how they are added in the component.


LWC follows kebab case ie if you are adding any LWC component inside another
component you will have to add in kebab case form while in AURA it will be added without
kebab case for example :
We have component with name “childLWCComponent”
In LWC it will be added as <c-child-l-w-c-component/>
In Aura it will be added as <c:childLWCComponent/>

38. What is LMS ?

Ans: 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.

40. Do we have application events in LWC?

Ans: We don’t have application event as such in LWC like Aura rather we have LMS in
LWC to communicate between components which are not part of same hierarchy.

41. How can we navigate user from LWC component to record


detail page?

Ans: Can be done using NavigationMixin service


Whatsapp Chat

42. Do we have force:createRecord equivalent in LWC?


Call us on:  IN +91 93478 54179 , 93467 64857 , USA +1 (415) 529-7271 || Request Call Back || Please call to USA number during USA day time.

https://www.crsinfosolutions.com/61-lwc-lightning-web-component-interview-questions/ 12/27
05/06/2024, 16:32 61 LWC Lightning Web Component Interview Questions and Answers

Ans: Using navigation mixin only you can also create new record where you define object
, action as new and pass any default values you want to set.

43. What is render() , is it part of lifecycle hook? Why do we use


it ?

Ans: Render is not part of lifecycle hook its a protected function, we only use it if we have
imported multiple templates in our component and we want to render particular template
on meeting certain criteria.

Enroll in our Salesforce training for a career-building experience with certification


preparation and real-time projects. Learn from faculty with over 15 years of industry
experience, ensuring you gain the skills needed to excel.

44. Can I get current user ID in LWC without apex?

Ans: Yes we can get current user ID without apex by simply importing
import Id from ‘@salesforce/user/Id’

45. What is difference between ‘==’ and ‘===’ ?

Ans: Both are used to compare two variables but == doesnt take data type into
consideration and does type coercion ie interpreter tries to automatically convert data
types to match the values while in === case if data type is not same it will always return
false.
For example :
2==”2” will return True (Type coercion happens)
2===”2” will return False ( No Type coercion)

46. What is String interpolation ? [important interview questions


and Salesforce Lightning]

Ans: It means simply when string literal is evaluated all the placeholders added into it are
calculated at run time and replaced in string with values. Place holder can be anything a
variable , expression even a function call. In javascript its performed using (backtick).

For example:
Whatsapp Chat

Call us on:  IN +91 93478 54179 , 93467 64857 , USA +1 (415) 529-7271 || Request Call Back || Please call to USA number during USA day time.

https://www.crsinfosolutions.com/61-lwc-lightning-web-component-interview-questions/ 13/27
05/06/2024, 16:32 61 LWC Lightning Web Component Interview Questions and Answers

const greeting = 'Hello';


const who = 'World';

const message =${greeting}, ${who}!`;


message; // => 'Hello, World!'

47. What are template literals? What is the use?

Ans: In javascript string interpolation is performed using template literals.


Template literals are created using (`) backtick character apart from string interpolation
they also are used for adding multi-line strings without having to use “\n”

For example:

console.log('string text line 1\n' +


'string text line 2');
console.log(`string text line 1
string text line 2`);
//Both will result in same output

48. Can i call function annotated with @AuraEnabled(cacheable=


true) imperatively ?

Ans: Yes

49. Can we do DML in method annotated with


@AuraEnabled(cacheable= true)?

Ans: No we cant do DML inside any method annotated with cacheable = true , you will
receive an error as DMLLimit Exception.

50. How to refresh cache when calling method imperatively ?

Ans: We have to use getRecordNotifyChange(RecordIds) which refreshes the LDS cache


providing you the latest data this will work only if cacheable = true was there.
Otherwise we will have to call the function again from our js to get the latest data.

Part – 2 | 50 LWC Lightning Web Component Interview


Questions Whatsapp Chat

Call us on:  IN +91 93478 54179 , 93467 64857 , USA +1 (415) 529-7271 || Request Call Back || Please call to USA number during USA day time.

https://www.crsinfosolutions.com/61-lwc-lightning-web-component-interview-questions/ 14/27
05/06/2024, 16:32 61 LWC Lightning Web Component Interview Questions and Answers

51. When do we face error of “Cant assign to Read only property”


in LWC?

Ans: This error usually occurs when you are trying to make changes to a property which is
marked as @api , ideally you should clone the value then make the changes to it.

52. How can I evaluate expression in situation like <template


if:true = {someVariable % 7==0}

Ans: We cant add expressions directly in html file rather what we can do is create getter
which will evaluate value for us which we can use in html like below :

get isMod7() { return this.index % 7 == 0; }


<template if:true ={isMod7}

53. Why do we put constants outside of class in LWC?

Ans: We cant put constants inside a class or function in javascript its illegal for example
below piece of code will throw you an error.

export default class someClass extends LightningElement {


const someVar = ‘someValue’ ;
}

54. How to query all lightning-input , combobox, radio buttons


using one querySelector or do I have to use multiple ?

Ans: We can query all of them using one query selector only no need to write multiple for
each tag. We can pass all tags (,) separated to query all.

const allValid = [...this.template.querySelectorAll('lightning-input,lightning-com

If you are wondering why are we using (…) spread operator before querySelectorAll its
because querySelector returns you the nodelist and using spread operator we convert it to
array of items otherwise we wouldnt be able to use array functions like map or reduce.
Whatsapp Chat
55. What is reduce method in JS?
Call us on:  IN +91 93478 54179 , 93467 64857 , USA +1 (415) 529-7271 || Request Call Back || Please call to USA number during USA day time.

https://www.crsinfosolutions.com/61-lwc-lightning-web-component-interview-questions/ 15/27
05/06/2024, 16:32 61 LWC Lightning Web Component Interview Questions and Answers

Reduce method calls the reducer function (callback function) for each item of the array to
reduce the whole array into single value.

Remember it doesnt change the actual array

array.reduce((accumulator , currentVal , currentIndex , array)=>{},0)

As the name suggests accumulator collects all the value


currentVal – denotes the current val of array
currentIndex – denotes the index of current val of array [optional]
Array – array object being passed. [optional]

Remember : If default value is passed accumulator is set to default value and index starts
with 0 , if no default value is passes accumulator is assigned 0th index value and
currentIndex starts from 1.

56. What would be the output of : 1+3+”4” ?

//A 44 because type coercion will take place.


statu
get statusVal(){
return statusVal ;
}
set statusVal(value){
this.statusVal = value;
}

renderedCallback(){
this.statusVal = ‘ABC’
}

Ans: Yes you will receive an error “Maximum depth exceeded” as in set function you are
again setting statusVal itself which means it will keep on setting itself (infinitely).

Interview Questions For Experienced


57. What is the difference between connectedCallback and
renderedCallback in LWC?
Whatsapp Chat

Call us on:  IN +91 93478 54179 , 93467 64857 , USA +1 (415) 529-7271 || Request Call Back || Please call to USA number during USA day time.

https://www.crsinfosolutions.com/61-lwc-lightning-web-component-interview-questions/ 16/27
05/06/2024, 16:32 61 LWC Lightning Web Component Interview Questions and Answers

Answer: In Lightning Web Components (LWC), lifecycle hooks are special methods that
allow developers to execute code at specific points during a component’s lifecycle. Two of
the most commonly used lifecycle hooks are connectedCallback and
renderedCallback . These hooks provide opportunities to run code when a component is
inserted into the DOM and after it has been rendered, respectively. Understanding the
differences between these hooks is crucial for effectively managing component
initialization and updates.

connectedCallback is called when the element is inserted into the DOM.


renderedCallback is called after every render of the component.

Code Example:

import { LightningElement } from 'lwc';

export default class LifecycleDemo extends LightningElement {


connectedCallback() {
console.log('Component inserted into the DOM');
}

renderedCallback() {
console.log('Component rendered');
}
}

58. How can you pass data between LWC components?

Answer:

In Lightning Web Components (LWC), passing data between components is a common


requirement for creating interactive and dynamic applications. There are several ways to
achieve this, depending on the relationship between the components. The most common
methods include using public properties, custom events, and the Lightning Message
Service (LMS). Understanding these methods is crucial for building robust and
maintainable applications.

Code Explanation

1. Using Public Properties Public properties are used to pass data from Whatsapp
a parent Chat
component to a child component. The child component exposes a public property using
Call us on:  IN +91 93478 54179 , 93467 64857 , USA +1 (415) 529-7271 || Request Call Back || Please call to USA number during USA day time.

https://www.crsinfosolutions.com/61-lwc-lightning-web-component-interview-questions/ 17/27
05/06/2024, 16:32 61 LWC Lightning Web Component Interview Questions and Answers

the @api decorator, and the parent component binds data to this property.

Code Example:

// Child Component (childComponent.js)


import { LightningElement, api } from 'lwc';

export default class ChildComponent extends LightningElement {


@api message;
}

// Child Component Template (childComponent.html)


<template>
<p>{message}</p>
</template>

// Parent Component (parentComponent.js)


import { LightningElement } from 'lwc';

export default class ParentComponent extends LightningElement {


parentMessage = 'Hello from Parent';
}

// Parent Component Template (parentComponent.html)


<template>
<c-child-component message={parentMessage}></c-child-component>
</template>

In this example, the parent component ( parentComponent ) passes the parentMessage


property to the child component ( childComponent ). The child component uses the @api
decorator to declare the message property as public, allowing it to receive the value from
the parent.

2. Using Custom Events Custom events are used to pass data from a child component
to a parent component. The child component dispatches an event with the data, and the
parent component listens for this event and handles the data.

Code Example:

// Child Component (childComponent.js)


import { LightningElement } from 'lwc'; Whatsapp Chat

export default class ChildComponent extends LightningElement {


Call us on:  IN +91 93478 54179 , 93467 64857 , USA +1 (415) 529-7271 || Request Call Back || Please call to USA number during USA day time.

https://www.crsinfosolutions.com/61-lwc-lightning-web-component-interview-questions/ 18/27
05/06/2024, 16:32 61 LWC Lightning Web Component Interview Questions and Answers

handleClick() {
const event = new CustomEvent('myevent', { detail: 'Hello from Child' });
this.dispatchEvent(event);
}
}

// Child Component Template (childComponent.html)


<template>
<button onclick={handleClick}>Click Me</button>
</template>

// Parent Component (parentComponent.js)


import { LightningElement } from 'lwc';

export default class ParentComponent extends LightningElement {


handleEvent(event) {
console.log(event.detail);
}
}

// Parent Component Template (parentComponent.html)


<template>
<c-child-component onmyevent={handleEvent}></c-child-component>
</template>

Explanation: In this example, the child component ( childComponent ) dispatches a


custom event ( myevent ) with a message in the detail property when a button is clicked.
The parent component ( parentComponent ) listens for this event and handles the data in
the handleEvent method.

3. Using Lightning Message Service (LMS) The Lightning Message Service (LMS) is
used to communicate between components that do not have a direct parent-child
relationship, even if they are in different parts of the application.

Code Example:

// Message Channel (messageChannel.js-meta.xml)


<?xml version="1.0" encoding="UTF-8"?>
<MessageChannel xmlns="http://soap.sforce.com/2006/04/metadata">
<masterLabel>SampleMessageChannel</masterLabel>
<isExposed>true</isExposed>
</MessageChannel>

// Publisher Component (publisherComponent.js) Whatsapp Chat


import { LightningElement } from 'lwc';
import
Call us on: {INcreateMessageContext,
+91 93478 54179 , 93467 64857 ,releaseMessageContext, publish
USA +1 (415) 529-7271 || Request Call } from
Back || Please call to USA'lightning/me
number during USA day time.

https://www.crsinfosolutions.com/61-lwc-lightning-web-component-interview-questions/ 19/27
05/06/2024, 16:32 61 LWC Lightning Web Component Interview Questions and Answers

import SAMPLEMC from '@salesforce/messageChannel/SampleMessageChannel__c';

export default class PublisherComponent extends LightningElement {


context = createMessageContext();

handleClick() {
const message = { message: 'Hello from Publisher' };
publish(this.context, SAMPLEMC, message);
}

disconnectedCallback() {
releaseMessageContext(this.context);
}
}

// Publisher Component Template (publisherComponent.html)


<template>
<button onclick={handleClick}>Publish Message</button>
</template>

// Subscriber Component (subscriberComponent.js)


import { LightningElement, wire } from 'lwc';
import { createMessageContext, releaseMessageContext, subscribe, unsubscribe } fro
import SAMPLEMC from '@salesforce/messageChannel/SampleMessageChannel__c';

export default class SubscriberComponent extends LightningElement {


subscription = null;

context = createMessageContext();

@wire(MessageContext)
messageContext;

connectedCallback() {
this.subscription = subscribe(
this.messageContext,
SAMPLEMC,
(message) => this.handleMessage(message)
);
}

disconnectedCallback() {
unsubscribe(this.subscription);
releaseMessageContext(this.context);
}

handleMessage(message) {
console.log('Received message:', message);
}
} Whatsapp Chat

// us
Call Subscriber Component
on:  IN +91 93478 Template
54179 , 93467 (subscriberComponent.html)
64857 , USA +1 (415) 529-7271 || Request Call Back || Please call to USA number during USA day time.

https://www.crsinfosolutions.com/61-lwc-lightning-web-component-interview-questions/ 20/27
05/06/2024, 16:32 61 LWC Lightning Web Component Interview Questions and Answers

<template>
<p>Check console for received messages</p>
</template>

59. How can you communicate from child to parent component in


LWC?

Answer:

In Lightning Web Components (LWC), communication between components is essential


for creating dynamic and interactive applications. While passing data from parent to child
components is straightforward using public properties, communicating from a child
component to a parent component requires a different approach. This is typically achieved
using custom events. Custom events allow child components to send messages or data to
their parent components, facilitating a two-way interaction within the component hierarchy.

Code Explanation

Custom Events Custom events in LWC are used to enable child-to-parent


communication. The child component dispatches an event with a specified name and
optional data payload, and the parent component listens for this event and handles the
data accordingly. This method allows for flexible and efficient communication between
components that maintains the decoupled nature of web components.

Code Example:

// Child Component (childComponent.js)


import { LightningElement } from 'lwc';

export default class ChildComponent extends LightningElement {


handleClick() {
const event = new CustomEvent('myevent', { detail: 'Hello from Child' });
this.dispatchEvent(event);
}
}

// Child Component Template (childComponent.html)


<template>
<button onclick={handleClick}>Click Me</button> Whatsapp Chat
</template>
Call us on:  IN +91 93478 54179 , 93467 64857 , USA +1 (415) 529-7271 || Request Call Back || Please call to USA number during USA day time.

https://www.crsinfosolutions.com/61-lwc-lightning-web-component-interview-questions/ 21/27
05/06/2024, 16:32 61 LWC Lightning Web Component Interview Questions and Answers

// Parent Component (parentComponent.js)


import { LightningElement } from 'lwc';

export default class ParentComponent extends LightningElement {


handleEvent(event) {
console.log(event.detail);
}
}

// Parent Component Template (parentComponent.html)


<template>
<c-child-component onmyevent={handleEvent}></c-child-component>
</template>

Explanation:

1. Child Component:

handleClick Method: The child component defines a method handleClick that


dispatches a custom event named myevent with a detail payload containing the
message ‘Hello from Child’.

Event Dispatching: The event is created using the CustomEvent constructor,


which takes the event name and an options object where the detail property
carries the data.

Template: The child component’s template includes a button that triggers the
handleClick method when clicked.

2. Parent Component:
Event Listener: The parent component template listens for the myevent event
using the onmyevent attribute and maps it to the handleEvent method.

handleEvent Method: This method logs the received event detail to the console,
demonstrating how the parent component can react to events dispatched by the
child component.

60. How do you handle asynchronous operations in LWC?


Whatsapp Chat
Answer:

Call us on:  IN +91 93478 54179 , 93467 64857 , USA +1 (415) 529-7271 || Request Call Back || Please call to USA number during USA day time.

https://www.crsinfosolutions.com/61-lwc-lightning-web-component-interview-questions/ 22/27
05/06/2024, 16:32 61 LWC Lightning Web Component Interview Questions and Answers

Handling asynchronous operations in Lightning Web Components (LWC) is crucial for


managing tasks such as fetching data from a server, processing user inputs, and
performing background computations. Asynchronous operations ensure that the user
interface remains responsive while waiting for these tasks to complete. In LWC,
asynchronous code can be managed using JavaScript’s Promises and the async / await
syntax, which provide a clean and efficient way to handle operations that take time to
complete.

Code Explanation

Using Promises and async / await JavaScript Promises represent the eventual
completion (or failure) of an asynchronous operation and its resulting value. The async /
await syntax is a modern way to work with Promises, allowing developers to write
asynchronous code that appears synchronous, making it easier to read and maintain.

Key Points:

Promises: Represent asynchronous operations and can be handled using .then()

and .catch() methods.


async/await: Syntactic sugar built on top of Promises, allowing for a more readable
and concise code structure.

Example Use Case: In the provided code example, an asynchronous operation is


performed in the connectedCallback method using the async / await syntax. The
fetchData method, presumably an Apex method or any other asynchronous function, is
awaited, ensuring that the data is fetched before further execution.

Code Snippet:

import { LightningElement, track } from 'lwc';


import fetchData from '@salesforce/apex/DataController.fetchData';

export default class AsyncDemo extends LightningElement {


@track data;

async connectedCallback() {
this.data = await fetchData(); Whatsapp Chat

Call us on:  IN +91 93478 54179 , 93467 64857 , USA +1 (415) 529-7271 || Request Call Back || Please call to USA number during USA day time.

https://www.crsinfosolutions.com/61-lwc-lightning-web-component-interview-questions/ 23/27
05/06/2024, 16:32 61 LWC Lightning Web Component Interview Questions and Answers

}
}

Explanation:

1. connectedCallback Method: The connectedCallback lifecycle hook is used here to


fetch data as soon as the component is inserted into the DOM. This ensures the initial

data is available when the component is rendered.


2. async Keyword: Declares the connectedCallback function as asynchronous,
allowing the use of await within it.

3. await Keyword: Pauses the execution of the connectedCallback function until the
fetchData Promise resolves. This ensures that this.data is assigned the fetched
data before the method completes.

By using async / await , the code becomes more readable and easier to maintain
compared to traditional Promise chaining with .then() and .catch() . This approach
ensures that asynchronous operations are handled efficiently, keeping the user interface
responsive and enhancing the overall user experience.

61. How can you conditionally render elements in LWC?

Answer:

In Lightning Web Components (LWC), conditionally rendering elements allows developers


to control the visibility of parts of the component’s template based on the component’s
state. This is essential for creating dynamic and responsive user interfaces. LWC provides
template directives like if:true and if:false to conditionally display elements based on
boolean expressions. These directives enable developers to show or hide elements
without having to manipulate the DOM directly, leading to cleaner and more maintainable
code.

Code Explanation

Using Template Directives if:true and if:false The if:true and if:false
Whatsapp Chat
directives in LWC are used to conditionally render parts of the template based on the

Call us on:  IN +91 93478 54179 , 93467 64857 , USA +1 (415) 529-7271 || Request Call Back || Please call to USA number during USA day time.

https://www.crsinfosolutions.com/61-lwc-lightning-web-component-interview-questions/ 24/27
05/06/2024, 16:32 61 LWC Lightning Web Component Interview Questions and Answers

value of a boolean property in the component’s JavaScript class. When the condition
evaluates to true, the element is rendered; otherwise, it is not included in the DOM.

Key Points:

if:true Directive: Renders the element if the condition is true.


if:false Directive: Renders the element if the condition is false.
Reactive Properties: The condition is typically a reactive property, ensuring that the

template updates automatically when the property’s value changes.

Example Use Case: In the provided code example, the component uses the if:true
directive to render an element only when a boolean property ( isVisible ) is true. This
allows the developer to control the visibility of elements based on the component’s state.

<template if:true={isVisible}>
<p>This is visible</p>
</template>
<template if:false={isVisible}>
<p>This is hidden</p>
</template>

// JS
import { LightningElement, track } from 'lwc';

export default class ConditionalRender extends LightningElement {


@track isVisible = true;
}

Explanation:

1. if:true and if:false Directives: The template uses these directives to

conditionally render paragraphs based on the value of the isVisible property.


2. Reactive Property: The isVisible property, decorated with @track , ensures that

any changes to its value automatically update the DOM.


3. Conditional Rendering: When isVisible is true, the first paragraph (“This is
visible”) is rendered. When isVisible is false, the second paragraph (“This is
Whatsapp Chat
hidden”) is rendered.
Call us on:  IN +91 93478 54179 , 93467 64857 , USA +1 (415) 529-7271 || Request Call Back || Please call to USA number during USA day time.

https://www.crsinfosolutions.com/61-lwc-lightning-web-component-interview-questions/ 25/27

You might also like