As Salesforce world is moving towards Lightning Web components (LWC), So today I will share the scenario-based Lightning web components interview questions with you.
Asking simple straightforward questions in Salesforce is history. Few years back Salesforce certified people were very less. Hence criteria was just to check whether that person know about Salesforce or not.
So questions used to be:
• What are Lightning Web Components (LWC)?
• What is Lightning Framework in Salesforce?
• How is LWC different from Aura?
• What is the use of a Lightning Component Framework?
• In how many ways can lightning components be made?
• What are the different Lightning page types?
etc.
If you notice above questions are crisp to the point. But now since in market there are many Salesforce certified people above style of interview doesn't work. One could easily memories these.
Now the style of asking questions is different for the interviewer. There is more focus on asking real time scenario questions rather than how etc.
Check Scenario Based LWC Interview Questions as one can have the theoretical knowledge. But the recruiters also check for scenario-based knowledge or Practical knowledge. Recruiters always ask tricky questions on the problems that one can face during implementation.
Only the person which has faced the problems while execution can only answer the questions.
In this blog series, I have tried to cover all LWC Scenario Based Interview Questions which are often asked by Salesforce Developer in an interview.
Please go through them in depth.
LWC ((Lightning Web Components)
Lightning Web Components are custom HTML elements build using the HTML Elements and modern JavaScript. We can build components using any of the models and can place these components on the same lightning page.
As of now, we have built a lightning component using the "Aura Components model". we can also build a lightning component using the "Lightning Web Components model".
Same but different
Instead of up to 8 files you only need 4. For one: all JavaScript (3 files) now lives in one ES6 JS file and we don't have an auradoc or svg file for now
For developing LWC we require "Salesforce Extensions for Visual Studio Code" and for deploying LWC from an org we require Salesforce CLI.
LWC - Developer Tool
Aura Components make use of own custom component model, custom templates, custom components, etc. while LWC is built on web standards and it makes use of web components, templates, custom elements which we have in web standards.
Both the Aura component, LWC make use of Security, LDS and Base lightning components.
1) Aura component and LWC can exist on the same lightning page.
2) Aura component can include LWC
Understanding the Lightning Web Component framework
The Lightning web component is the component-based framework built using SLDS (Salesforce Lightning Design System) and web components.
Lightning Web Components are custom HTML elements build using the HTML Elements and modern JavaScript.
Lightning Web Component framework has a rich set of out the box components and APIs to communicate with the Salesforce Database.
Why Lightning Web Component is lightweight?
Because the Lightning Web Components framework is built on the code which natively runs in the browser, most of the code that you write in them is standard HTML and JavaScript.
Unlike the Aura Component Framework, they don't need the additional resources to be loaded.
LWC- Component Structure
Similar to an AURA component, the main contents of a LWC are also html, JavaScript. There are optional content like CSS. But then in addition to these for LWC, an xml configuration file is also included which defines the metadata values for the component. So, a LWC component would look like:
myComponent folder
myComponent.html
myComponent.js
myComponent.js-meta.xml
myComponent.css
myComponent.svg
The folder and its files must follow these naming rules.
• Can’t contain a hyphen (dash)
• Must begin with a lowercase letter
• Can’t include whitespace
• Contain only alphanumeric or underscore characters
• Can’t end with an underscore
• Must be unique in the namespace
• Can’t contain two consecutive underscores
Interview Series
Let start the interview series on Scenario Based Interview Questions on Lightning Web Components (Between Interviewer & Interviewee).
Interviewer: What is LWC(Lightning Web Components)?
Interviewee: Lightning web components are custom HTML elements built using HTML and modern JavaScript. Lightning Web Components uses core Web Components standards and provides only what’s necessary to perform well in browsers supported by Salesforce.
• Custom HTML Components built using HTML and modern JS (ES 6)
• Supported by the same browsers as Lightning Experience.
• Uses latest version of JS.
Interviewer: Do you think Aura Web Components and Lightning Web Components can coexist together?
Interviewee: Yes, both Aura Lightning components and Lightning Web Components can coexist together.
Interviewer: What are the advantages of using Lightning Component Framework?
Interviewee: Here are some of the benefits of using the Lightning Component Framework.
1. It provides out-of-the-box components.
2. Rich Custom Component Ecosystem.
3. Fast Development.
4. Device-aware and Cross Browser Compatibility.
Interviewer: Explain the Lightning Web Component Bundle?
Interviewee: LWC bundle contains an HTML file, a JavaScript file, and a Metadata Configuration file and these files are created once we create a Lightning web component.
Component: HTML File
Every user interface (UI) component must have an HTML file with the root tag <template>
It should be saved as “<component>.html” like myComponent.html below.
Component: JavaScript File
All business logic for components is defined in a JavaScript file, and it’s written as “<component>.js”. To import a class, function, or variable declared in a module, use the “import” statement. To allow other code to use a class, function, or variable declared in a module, use the “export” statement.
Component: Metadata Configuration File
Every component must have a configuration file. The configuration file defines the metadata values for the component, including the design configuration for Lightning App Builder and Community Builder.
All LWC configuration settings are included in a metafile. For example, “<isexposed>” is set to true to expose the component in all orgs. We can define targets where we wanted to use our LWC using the “<target>” tag.
Above mentioned file are default ,we can also add CSS
, SVG
and other optional files like “Additional JavaScript file” with a unique name.
The file structure of Lightning Web Components
myComponent folder
myComponent.html
myComponent.js
myComponent.js-meta.xml
myComponent.css
myComponent.svg
Interviewer: What is the purpose of JavaScript file in Lightning Web Component bundle?
Interviewee: The JavaScript file defines the behavior of HTML element present in HTML file.
JavaScript files in Lightning web components are ES6 modules. By default, everything declared in a module is local—it’s scoped to the module.
To import a class, function, or variable declared in a module, use the import statement. To allow other code to use a class, function, or variable declared in a module, use the export statement.
Interviewer: What is difference between var and let in JS ?
Interviewee: 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.
Interviewer: What is Meta configuration file in Lightning Web Component?
Interviewee: The Meta configuration file defines the metadata values for the components.
If we don’t include a configuration file for our component, we get an error shown below when we push your changes.
Error Message :
"Cannot find Lightning Component Bundle
".
Interviewer: How can you display components HTML conditionally?
Interviewee: If we want to render HTML conditionally, add the if:true|false
directive to a nested <template>
tag that encloses the conditional content.
Interviewer: How we can iterate list in Lightning Web Component (LWC)?
OR How to iterate over an array in HTML file?
Interviewee: There are 2 ways of iterating your list in LWC templates :
1. for:each
2. Iterator
Whenever we use for:each
or Iterator
we need to use key directive on the element on which we are doing iteration. Key gives unique id to each item. Remember, without key we cannot do iteration.
When a list changes, the framework uses the key to re-render only the item that changed. It is used for performance optimization and isn’t reflected in the DOM at run time.
for:each
• When using the for:each directive, use for:item=”currentItem” to access the current item.
• To assign a key to the first element in the nested template, use the key={uniqueId} directive.
• You can use them for:index=”index” to access the current item index, it is optional.
Example :
HelloForEach.html
<template> <lightning-card title= "HelloForEach" icon-name= "custom:custom14" > <ul class = "slds-m-around_medium" > <template for :each={contacts} for :item= "contact" > <li key={contact.Id}> {contact.Name}, {contact.Title} </li> </template> </ul> </lightning-card> </template> |
HelloForEach.js
import { LightningElement } from 'lwc' ; export default class HelloForEach extends LightningElement { contacts = [ { Id: 1 , Name: 'Saurabh Samir' , Title: 'Salesforce Developer' , }, { Id: 2 , Name: 'Jack Jones' , Title: 'VP of Sales' , }, { Id: 3 , Name: 'Vivek Wali' , Title: 'CEO' , }, ]; } |
Output:
iterator
If you want add special behavior to the first or last item in a list, use the iterator directive, iterator:iteratorName={array}. Use the iterator directive on a template tag.
Use iteratorName to access these properties:
• value—The value of the item in the list. Use this property to access the properties of the array.
For example, iteratorName.value.propertyName.
• index—The index of the item in the list.
• first—A boolean value indicating whether this item is the first item in the list.
• last—A boolean value indicating whether this item is the last item in the list.
Sample Example:
HelloIterator.html
<template> <lightning-card title= "HelloIterator" icon-name= "custom:custom14" > <ul class = "slds-m-around_medium" > <template iterator:it={contacts}> <li key={it.value.Id}> <div if : true ={it.first} class = "list-first" ></div> {it.value.Name}, {it.value.Title} <div if : true ={it.last} class = "list-last" ></div> </li> </template> </ul> </lightning-card> </template> |
HelloIterator.js
import { LightningElement } from 'lwc' ; export default class HelloForEach extends LightningElement { contacts = [ { Id: 1 , Name: 'MK' , Title: 'Salesforce Developer' , }, { Id: 2 , Name: 'Ram' , Title: 'VP of Sales' , }, { Id: 3 , Name: 'Vivek ' , Title: 'CEO' , }, ]; } |
helloIterator.css
.list-first { border-top: 1px solid black; padding-top: 5px; } .list-last { border-bottom: 1px solid black; padding-bottom: 5px; } |
Output:
Interviewer: How we can pass data from HTML to JS controller?
Interviewee: We can use the onchange attribute to listen for a change to its value. When the value changes, the handleChange function in the JavaScript file executes.
Notice that to bind the handleChange function to the template, we use the same syntax, {handleChange}
Sample Example:
helloBinding.html
<template> <p>Hello, {greeting}!</p> <lightning-input label= "Welcome in SFDC Worlds...!!" value={greeting} onchange={handleChange}> </lightning-input> </template> |
helloBinding.js
import { LightningElement } from 'lwc' ; export default class HelloBinding extends LightningElement { greeting = 'LearnFrenzy' ; handleChange(event) { this .greeting = event.target.value; } } |
Output
Interviewer: What is LMS ?
Interviewee: 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.
Interviewer: Do we have application events in LWC?
Interviewee: 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.
Interviewer: How can we navigate user from LWC component to record detail page?
Interviewee: Can be done using NavigationMixin service.
Interviewer: Do we have force:createRecord equivalent in LWC?
Interviewee: 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.
Interviewer: Can I get current user ID in LWC without apex?
Interviewee: Yes we can get current user ID without apex by simply importing
1 | import Id from '@salesforce/user/Id' |
Interviewer: What is difference between ‘==’ and ‘===’ ?
Interviewee: Both are used to compare two variables but == doesn't 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)
Interviewer: What is String interpolation?
Interviewee: 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).
In lightning AURA components, we have used concatenation lot of time to join multiple strings. But now we need to change something in the lightning web component.
For example:
console.log( 'string1' + 'string2' + 'string3' ); |
Now we need to change our habits and learn something called interpolation.
Let's understand with the help of an example :
Example -1 :
const greeting = 'Hello' ;<br> const who = 'Salesforce LearnFrenzy!' ;<p></p> const message = ${greeting}, ${who}!`;<br> message; // => ‘Hello, Salesforce LearnFrenzy!' |
Example -2 :
function favouriteBlogs{ let firstBlog = 'Salesforce Official' ; const secondBlog = 'Salesforce LearnFrenzy' ; //Please observe the string Interpolation below console.log( 'My favourite blogs are ${firstBlog} and ${secondBlog}' ); } //Console > My favourite blogs are Salesforce Official and Salesforce LearnFrenzy |
As you can observe in the above code we need to just use ${firstBlog} instead of maintaining '+' signs.
Let/Const :
Of course, we are familiar with var in JavaScript before, but fortunately/unfortunately now we need to use Let/Const.
Let :
Whenever you want to reassign the value for any variable then we will define with Let variable.
It also signals that the variable will be used only in the block it's defined in, which is not always the entire containing function.
Const :
Whenever you use const then the identifier won't be reassigned further. The value will remain constant.
Interviewer: Why do we put constants outside of class in LWC?
Interviewee: 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' ; } |
Interviewer: What are template literals ? What is the use?
Interviewee: 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 |
Interviewer: What are the types of decorators in lightning web components and explain all three decorators in lightning web components?
Interviewee: The Lightning Web Components programming model has three decorators that add functionality to a property or function. The ability to create decorators is part of ECMAScript, but these three decorators are unique to Lightning Web Components.
1. @api: To expose a public property, decorate it with @api. An owner component that uses the component in its markup can access the component’s public properties.
2. @track: To track a private property’s value and re-render a component when it changes, decorate the property with @track. Tracked properties are also called private reactive properties.
3. @wire: To read Salesforce data, Lightning web components use a reactive wire service. When the wire service provisions data, the component re-renders.
Interviewer: What are the public properties in Lightning Web Component?
Interviewee: Public properties are reactive. If the value of a public property changes, the component re-renders. To expose a public property, decorate a field with @api. Public properties define the API for a component.
Interviewer: When do I use @track on a property ? Do I still need it considering all properties are by default reactive now?
Interviewee: After Spring 20 all the properties are made by default reactive i.e. we don't need @track for primitive properties. We still need it for array or object type properties.
Interviewer: Can I use multiple decorators on one property?
Interviewee: No we cant use multiple decorators on same property.
Interviewer: 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. You checked your apex code but could not figure out the issue. What could be one of the reason?
Interviewee: check whether you have used cacheable=true
along with @AuraEnabled annotation in the apex method.
Interviewer: Will the below code deploy? (Assuming all variables and apex class function exists).
@wire (getBikes,{bikeTypeId : this .bikeTypeId}) getBikes(error,data){ } |
Interviewee: No it wont when passing a variable in wire you should always use $ along with variable, it should be written like :
@wire (getBikes,{bikeTypeId : '$bikeTypeId' }) |
Interviewer: Why do we use $ when passing property in wire function, what does it mean?
Interviewee: $ 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.
Interviewer: Suppose you are using getRecord in LWC to get any field value from the current record. Now you need to pass the retrieved value to an apex method using wire approach. How can you pass the value?
Interviewee:
Example: exploreGetRecord.js
import { LightningElement, wire, api } from "lwc" ; //1. import the methods getRecord and getFieldValue import { getRecord, getFieldValue } from "lightning/uiRecordApi" ; //2. Import reference to the object and the fields import NAME_FIELD from "@salesforce/schema/Account.Name" ; import RATING_FIELD from "@salesforce/schema/Account.Rating" ; import INDUSTRY_FIELD from "@salesforce/schema/Account.Industry" ; const fields = [NAME_FIELD, RATING_FIELD, INDUSTRY_FIELD]; export default class ExploreGetRecord extends LightningElement { @api recordId; //3. Wire the output of the out of the box method getRecord to the property account @wire (getRecord, { recordId: "$recordId" , fields }) account; renderedCallback() { console.log( this .account.data); } //4. Fetch the field values from the record get name() { return getFieldValue( this .account.data, NAME_FIELD); } get rating() { return getFieldValue( this .account.data, RATING_FIELD); } get industry() { return getFieldValue( this .account.data, INDUSTRY_FIELD); } } |
exploreGetRecord.html
<template> <div class = "slds-m-around_medium" > <p><b>Account Name :</b>{name}</p><br> <p><b>Industry :</b> {industry}</p><br> <p><b>Rating :</b>{rating}</p> </div> </template> |
exploreGetRecord.js-meta.xml
<?xml version= "1.0" encoding= "UTF-8" ?> <apiVersion> 55.0 </apiVersion> <isExposed> true </isExposed> <targets> <target>lightning__AppPage</target> <target>lightning__RecordPage</target> <target>lightning__HomePage</target> </targets> </LightningComponentBundle> |
Now we can add this lwc component on the account detail page.
• Go to Home page
• Click Setup (Gear Icon) and select Edit Page.
• Under Custom Components, find your exploreGetRecord component and drag it on Account detail page.
• Click Save and activate.
We will have the following output.
Interviewer: 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 (getBikes,{bikeTypeId : '$bikeTypeId' }) getBikes({error,data}){ if (data){ this .someVar = data; this .error = undefined; } else if (error){ this .error = error; this .someVar = undefined ; } } |
Interviewee: 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 (getBikes,{bikeTypeId : '$bikeTypeId' }) getBikes(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)
Interviewer: Can we call a wire function inside a javascript function like below :
searchBikes(event){ @wire (getBikes,{bikeTypeId: '$bikeTypeId' } getBikes(data,error){ } } |
Assume searchBikes is being called on click of button? Will I be able to deploy the code ?
Interviewee: No you can't 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.
Interviewer: When is the wire method/property called in the lifecycle of a component ?
Interviewee: Wired service is called right after component is created i.e. after constructor and is again called when parameter that you are passing is made available.
Interviewer: What are lifecycle hooks in LWC ?
Interviewee: 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.
Interviewer: Is wire method called multiple times during lifecycle of component ?
Interviewee: Every time the @api record gets updated the wire method gets called again. So yes it might be called several times.
Interviewer: What is render() , is it part of lifecycle hook? Why do we use it ?
Interviewee: 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.
Interviewer: What is the difference in below two codes , will they both compile ? Give same results ?
Code -1:
@wire (getBikes) getBikes({data,error}){ if (data) console.log( 'print here' ); Else if (error) console.log( 'print in else' ); } |
Code -2
@wire (getBikes,{}) getBikes({error,data}){ if (data) console.log( 'print here' ); Else if (error) console.log( 'print in else' ); } |
Interviewee: Both will compile they are same.
Interviewer: Is it mandatory to use data,error only in wired method, can I use some other variable like below :
@wire (getBikes) getBikes({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 ?
Interviewee: 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.
Interviewer: Can I Deploy Component With Empty CSS File In Salesforce?
Interviewee: No we can't do that.
Interviewer: Can We Use CSS In LWC?
Interviewee: Yes, we can use CSS in LWC. There are different ways to add CSS to our components. One way is to create a static resource and include it in our component using the ltng:require
tag. Another way is to use the style tag in our component.
Interviewer: Are quick actions supported for LWC components ?
Interviewee: Quick actions are supported by LWC in Summer 21 or later orgs. LWC quick actions are only supported on record pages
Interviewer: How can i reference record ID of page in my component which is fired from quick action.
Interviewee: There are two types of quick actions in LWC :
Screen actions : Normal action which open a modal
Headless actions : Which don't have any html file rather just logic written in Js i.e. 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.
Interviewer: What is a promise in async transactions? What are it different stages.
Interviewee:
Promises are special objects in JavaScript which represents the success or failure value of an asynchronous operation.
When you create an asynchronous operation using promise, an object is returned to which you attach the callbacks for success and failure.
Basically, whatever operation you need to perform, you pass that as function to the promise. When the promise is executed you attach the success and handler function to it.
For example : when you call apex imperatively it returns you a promise object on the basis of object returned execution either goes into (then) i.e. transaction was successful or (catch) which means transaction failed.
Let's take an example of file upload. Assume that you want a file to be uploaded in an asynchronous way in the background. And you want to log success messages whenever the operation is completed.
I have created a simple promise method here.
new Promise(resolve => { console.log( "File upload started" ); window.setTimeout(resolve, 2000 ); // assume that file takes 2 seconds to upload. }).then((result) => { console.log( 'File is uploaded' ); }) console.log( 'This block of code continues and get executed before file upload.' ); |
Output for the above code will be:
File upload started This block of code continues and get executed before file upload. File is uploaded // after 2 seconds |
Now we will see how we can add the error handler.
new Promise(resolve => { console.log( "File upload started" ); window.setTimeout(resolve, 2000 ); }).then((result) => { throw new Error( "error" ); console.log( 'File is uploaded' ); }). catch (() => { console.log( 'File upload failed' ); // handle error here. }) |
Output for the above code will be:
File upload started File upload failed // after 2 seconds |
A Promise is in one of these states:
• pending: initial state, neither fulfilled nor rejected.
• fulfilled: meaning that the operation was completed successfully.
• rejected: meaning that the operation failed.
Interviewer: Why we use promises?
Interviewee: There are multiple reasons.
• It improves error handling, and you don't need to add custom error handling. No matter if the error is in the async operation or .then() method, it will be passed in .catch().
• It improves the readability of the code.
• We can chain multiple async operations.
• We have better control over the flow of the async operations.
Interviewer: Why Promises are so much important for Lwc? & What are the common use cases?
Interviewee: Promises are everywhere in LWC, this framework heavily uses promises. You are using promises if you are using these things from LWC. All things mentioned below are applications of Promises.
• @wire property or method
• imperative apex methods
• imperative calls to Lightning data service methods.
• loadScript to load external script from the static resource
• loadStyle to load external style from static resources.
If you have ever used imperative calls in lwc, you must have noticed that we use .then() and .catch() methods to handle success and error.
The Common Use Cases
The most common use case of promise is to load the external style/script in LWC. See the code used to load third party styles and scripts in the Lightning web component.
Promise.all([ loadScript( this , LIB + '/learfrenzy_lib.js' ), loadStyle( this , LIB + '/learnfrenzy_styles.css' ) ]) .then(() => { // do something when scipt and styles loaded. }) . catch (error => { this .dispatchEvent( new ShowToastEvent({ title: 'Error loading Libs' , message: error.message, variant: 'error' }) ); }); |
Another scenario could be when you want to chain imperative calls to two apex methods. For example if you have two apex methods methodA
and methodB
, now you want to pass the result of methodA
into methodB
, then you can do it like this.
methodA() .then((result) => (( this .output = result), methodB({ someparam: result }))) .then((result) => ( this .output = result)); |
Calling an API from JavaScript.
.then(response => { // process success }) . catch ( error => { // handle error here }) |
Interviewer: What are the downsides of promises?
Interviewee: One of the biggest downsides of the promises is callback hell. Callback hell is a series of nested calls to the promises.
Interviewer: What to understand Callback and Callback hell in JavaScript ?
Interviewee: Callback functions are functions passed as arguments to another function, which will be called in the function it was passed to.
They are basically functions that are executed only after a result is produced. Callbacks are an important part of asynchronous JavaScript.
The best example of this is window.setTimeout
. We pass a function to setCallout
, which gets called when the timeout is completed.
function myCallbackFunction(){ console.log( "in myCallbackFunction" ); } window.setTimeout(myCallbackFunction, 2000 ); |
Callback Hell: Callback Hell is essentially nested callbacks stacked below one another forming a pyramid structure. Every callback depends/waits for the previous callback, thereby making a pyramid structure that affects the readability and maintainability of the code.
In most simple words callback hell occurs when there are many functions you want to call async and you end up putting 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) { ... } ); }); }); |
Interviewer: Can i call function annotated with @AuraEnabled(cacheable= true) imperatively ?
Interviewee: Yes
Interviewer: Can we do DML in method annotated with @AuraEnabled(cacheable= true)?
Interviewee: No we cant do DML inside any method annotated with cacheable = true , you will receive an error as DMLLimit Exception.
Interviewer: How to refresh cache when calling method imperatively ?
Interviewee: 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.
Interviewer: When do we face error of "Cant assign to Read only property" in LWC?
Interviewee: 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.
Interviewer: How to query all lightning-input , combobox, radio buttons using one querySelector or do I have to use multiple ?
Interviewee: 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 wouldn't be able to use array functions like map or reduce.
Interviewer: How can expression functions similar to Visualforce and Lightning Aura Components be achieved within lightning web components?
For example, <template if:true={index % 7 == 0}><br></template>
expression index % 7 == 0
is not complying at all.
accountList.html
<template> <template if : true ={accounts.data}> <template for :each={accounts.data} for :item= 'item' for :index= 'index' > <!--LWC DOES NOT SUPPORT EXPRESSION FUNCTIONS--> <!--<template if : true ={index % 7 == 0 }><br></template>--> {item} </template> </template> </template> |
accountList.js
import {LightningElement, wire} from 'lwc' ; import getAccounts from '@salesforce/apex/TestController.getAccounts' ; export default class AccountList extends LightningElement { @wire (getAccounts) accounts; } |
Since LWC doesn't support Expression Functions, I'd like to know how to implement them.
Interviewee: There are multiple options. First, note, that all computations are in JavaScript, not in the markup.
Option -1 :
You implement the display of your {item} (which is currently only the JSON object), into a dedicated component AccountListItem
.
import {LightningElement, api} from 'lwc' ; export default class AccountListItem extends LightningElement { @api index; @api item; get isMod7() { return this .index % 7 == 0 ; } } |
Option-2 :
You use a wired function instead of a wired property. And then do some fun stuff with a changed data model. Although this is hacky.
import {LightningElement, wire, track} from 'lwc' ; import getAccounts from '@salesforce/apex/TestController.getAccounts' ; export default class AccountList extends LightningElement { @wire (getAccounts) wiredAccounts({ error, data}) { if (error) { // do error handling, please } else if (data) { this .accounts = data.map((acct, index) => { return { acct: acct, isMod5: index % 7 == 0 ? true : false } }) } } |
No comments:
Post a Comment