LWC Interview Questions and Answers
LWC Interview Questions and Answers
DHANANJAY AHER
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)
2.What do you mean by cacheable = true annotations ?
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)
3.@wire(getBoats,{boatTypeId : this.boatTypeId})
getBoats(error,data){}
Will the above code deploy? (Assuming all variables and apex class function exists).
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?
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.
5.See the below code and answer the following question:
If I want to refresh the wired data in the above function, can I call
refreshApex(this.someVar) ?
@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){
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.
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.
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.
11.Is it mandatory to use data,error only in wired method, can I use some other
variable like below :
@wire(getBoats)
getBoats({myData,myError}){
if(mydata)
console.log(‘i am in data’);
else if(myError)
console.log(‘I am in error’);
Will the code deploy successfully or I will receive an error ? Salesforce Lightning LWC interview
questions and answersAns: 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.
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.
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.
14.Are quick actions supported for LWC components ?
Ans: Quick actions are supported by LWC in Summer 21 or later orgs. LWC quick actions
are only supported on record pages.
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.
16.What is a promise in async transactions? What are it different stages.
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.
17.What is the difference between Promise and Promise.all
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.
18.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.
19.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
20.How do I retrieve elements on the basis of ID?
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.
21.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
22.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.
23.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.
24.When you fire an event, can i capture it in same template/ component ?
Ans: No
25.Is bubble : false and composed : true possible in an event ?
Ans: No
26.What is the difference between below :
a. Bubble : false and composed : false
b. Bubble : true and composed : true
c. Bubble : true and composed : false
27.What are callback functions in LWC ?
Ans: Callback functions are nothing but functions passed as parameter into other
functions.
28.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.
29.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)
{ ... }
);
});
});
30.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
31.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
32.Can I use multiple decorators on one property ?
Ans: No we cant use multiple decorators on same property.
33.Can I deploy component with empty css file ?
Ans: No we cant do that
34.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.
35.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/>
36.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.
37.Do we have application events in LWC?
Ans: We dont 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
38.How can we navigate user from LWC component to record detail page?
Ans: Can be done using NavigationMixin service
39.Do we have force:createRecord equivalent in LWC?
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.
40.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.
41.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’
42.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)
43.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:
const greeting = 'Hello';
const who = 'World';
const message = ${greeting}, ${who}!`;
message; // => ‘Hello, World!’
44.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
45.Can i call function annotated with @AuraEnabled(cacheable= true) imperatively
?
Ans: Yes
46.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.
47.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.
48.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.
49.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}
50.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’ ;
51.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-
combobox,lightning-radio-group’)];
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.
52.What is reduce method in JS ?
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
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.
53.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).