20 Essential Salesforce LWC Interview Questions for Developers – Part 1

Part 1 - 20 Interview Questions on Salesforce LWC.png
Chinmaya By Chinmaya
39 Min Read

Introduction

Lightning Web Components (LWC) are a must-know for Salesforce developers, especially in technical interviews. To help you prepare, I’ve created a series of blog posts with 200 LWC interview questions.

In Part 1, we’ll cover the first 20 questions, focusing on LWC basics, decorators, lifecycle hooks, and event handling. Whether you’re new to LWC or brushing up your skills, this post is a great starting point.

So, without wasting more time, let’s start..

1. What is Salesforce Lightning Web Components (LWC)?

    • Salesforce Lightning Web Components (LWC) is a modern way for building fast, lightweight, and responsive user interfaces on the Salesforce platform
    • It follows latest web standards, making it faster, easier, and more flexible than the older Aura framework.
    • LWC helps Salesforce developers to create user interface (UI) components more efficiently and with better performance.

Key Features of LWC are:

    1. Lightweight and Fast: Built on modern web standards for better performance.

    2. Reusability: Create reusable components for consistent UI across apps.

    3. Two-Way Data Binding: Simplifies data synchronization between components.

    4. Event-Driven Architecture: Enables communication between components using events.

    5. Lifecycle Hooks: Provides methods like connectedCallback and renderedCallback for better control.

    6. Security: Uses Shadow DOM to encapsulate components and prevent style conflicts.

    7. Interoperability: Works seamlessly with Aura components and other Salesforce features.

If you want to learn more about Salesforce LWC, then I would recommend you to explore the post below.

2. What are the advantages of using LWC over Aura Components?

    1. Better Performance: LWC is faster than Aura components because it uses modern web standards like JavaScript ES6, which are optimized by browsers.
      This results in faster rendering and better overall performance.
    2. Simpler Syntax:
      LWC uses a cleaner, simpler syntax based on standard JavaScript and HTML, making it easier to learn and work with compared to the more complex Aura syntax.
    3. Smaller Bundle Size:
      LWC components are lightweight, leading to smaller bundle sizes, which reduces the amount of data that needs to be loaded, improving load times.
    4. Modern Web Standards:
      LWC is built on web standards like custom elements, Shadow DOM, and ES modules, making it more compatible with other frameworks and easier for developers to use modern tools and libraries.
    5. Reactivity:
      LWC has built-in reactivity, meaning that when data changes, the UI updates automatically without needing extra code, making it easier to manage dynamic content.
    6. Better Developer Experience:
      With LWC, developers can take advantage of features like easier debugging, better integration with tools like Jest for testing, and better support for browser features.
    7. Component Isolation:
      LWC uses Shadow DOM.
      This keeps the component’s structure, style, and behaviour separate, so they don’t affect the rest of the page.

In short, LWC provides better performance, simplicity, and developer experience compared to Aura components, making it the preferred choice for building Salesforce applications.

3. Explain the LWC component folder structure

1. HTML File (componentName.html):

This file contains the structure of your LWC component. It defines the layout using HTML tags.

2. JavaScript File (componentName.js):

Javascript file contains the logic for your LWC component.
It defines the behaviour using JavaScript, such as handling user events or making data requests.

3. CSS File (componentName.css): (optional)

CSS file contains the styling for your component. It controls the look and feel of the component, like colours, fonts, and layout.

4. Meta File (componentName.xml)

This file contains the configuration details about the component.
In this file, we define things like the component’s visibility, target audience, and where it can be used (e.g., in Lightning Pages, record pages, etc.).

Example Folder Structure

				
					myComponent/  
├── myComponent.html  
├── myComponent.js  
├── myComponent.css  
└── myComponent.js-meta.xml
				
			

4. What is a shadow DOM, and how is it used in LWC?

    • Shadow DOM is a web technology that lets you keep your LWC component separate from the rest of the webpage.
    • It creates a hidden “shadow” tree inside your component, ensuring its structure, styles, and behaviour don’t affect or get affected by other parts of the page.
    • This prevents conflicts with other parts of the webpage.

How is Shadow DOM Used in LWC?

    1. Encapsulate Styles: CSS defined in a LWC component doesn’t leak out or affect other components.

    2. Enhance Security: Prevents external scripts from accessing or modifying the component’s internal structure.

    3. Isolation:
      The styles and DOM inside the component are completely separate from the rest of the page. This prevents style conflicts or JavaScript interactions with other components.
    4. Component Integrity:
      Since each LWC component has its own shadow DOM, changes in one component won’t affect others, making components more predictable and easier to maintain.

Important:
Shadow DOM ensures that – If you define some CSS styles in your LWC component, those styles won’t accidentally change the appearance of other elements on the page

Explore the post below to learn more about Shadow DOM Boundaries in LWC

5. What are the prerequisites for developing LWC components?

To start developing Lightning Web Components (LWC), you need a few basic things in place:

  1. Salesforce Account:
    • You need access to a Salesforce organization (Org), either a Developer Edition, a Sandbox, or a Salesforce Trailhead Playground to create and test LWC components.
  2. Basic Knowledge of Web Development:
    • You should be familiar with core web technologies:
      • HTML: For structuring the component.
      • CSS: For styling the component.
      • JavaScript: The logic of your component is present in the JavaScript file.
  3. Salesforce Platform Basics:
    • Understanding Salesforce concepts like Objects, Fields, and Apex (for backend logic) will be helpful.
  4. Salesforce Developer Tools:
    • Salesforce CLI: A command-line interface to interact with Salesforce Org.
    • VS Code: A text editor with Salesforce extensions for developing and deploying LWC components.
  5. Salesforce Lightning Design System (SLDS) (optional):
    • Knowledge of SLDS helps in designing consistent user interfaces that match Salesforce’s design guidelines.

6. Explain the use of @track in LWC

    • The @track decorator in LWC is used to make a JavaScript property Reactive.
    • When you add @track to a property, any changes to that property in the JavaScript code, the component’s UI gets automatically updated.
    • This means your LWC component will re-render whenever the tracked property’s value changes.

Please Note:

    1. However, as of LWC API version 39.0, @track is no longer required for primitive properties (like strings, numbers, booleans) as they are reactive by default. It is still used for making object or array properties reactive when their internal values change.
    2. The @track decorator ensures reactivity within the component, but it does not directly track changes from the Salesforce backend.
    3. If the data is coming from the backend, you would need to handle it (e.g., using Apex methods or data services) and then update the tracked property.

Example 1:

				
					import { LightningElement, track } from 'lwc';

export default class MyComponent extends LightningElement {
    @track name = 'John';  // This property is now reactive
}
				
			

Example 2:

				
					@track myObject = { key: 'value' }; // Ensures reactivity for object changes.
				
			

In Simple Words

The @track decorator tells the LWC to watch the property for any changes. If there are any changes to the property, then update the LWC component’s UI automatically.

Explore the post below to learn more about @track Decorator in LWC

7. What is the difference between @track, @api, and @wire in LWC?

@track, @api and @wire are 3 different decorators used in Salesforce LWC.

1. @track

    • Purpose: Makes a property reactive. Changes to the property trigger UI updates. Primitive properties are reactive by default, but @track is used for objects/arrays to ensure reactivity when their internal values change.
    • Use case: Used for internal properties that you want to track and update in your component.

Example:

				
					//JavaScript code
@track name = 'John';  // UI updates when 'name' changes
				
			

2. @api

    • Purpose: @api is used to expose a property or method in a Child LWC component, allowing it to be accessed by other components, such as parent components or sibling LWC components.
      Properties marked with @api are reactive and can be passed from a parent component.
    • Use case: @api is used in Child component, when you want to:
      • Pass data from the Parent component to the Child component.

      • Call methods in the Child component from the Parent.

Example:

Parent Component (HTML):

				
					<template>
    <c-child-component message-from-parent="Hello, Child!"></c-child-component>
</template>
				
			

Child Component (JavaScript):

				
					import { LightningElement, api } from 'lwc';

export default class ChildComponent extends LightningElement {
    @api messageFromParent; // Property exposed to parent
}
				
			

Child Component (HTML):

				
					<template>
    <p>{messageFromParent}</p>
</template>
				
			

In this example:

    1. The parent LWC component passes a message (message-from-parent) to the child LWC component.
    2. The child component uses @api to define a property (messageFromParent) that receives the value.
    3. The message is displayed in the child component’s UI.

3. @wire

    • Purpose: @wire is used to read data from Salesforce (like from Apex or a REST API) and automatically updates the component when the data changes.
    • Use case: It is used for fetching data from Salesforce or invoking Apex methods in a reactive way.

Example:

				
					@wire(getContacts) contacts;  // Automatically fetches data
				
			

In Summary

    1. @track: is used to make a property reactive.
    2. @api: is used to expose Child LWC component’s properties or methods to parent components.
    3. @wire: is used to fetch and automatically update data from Salesforce or to invoke Apex class.

Explore the post below to learn more about 3 Decorators in Salesforce LWC

8. How do you pass data between parent and child components in LWC?

In Salesforce LWC, you can pass data between parent and child components in two main ways:

1. Sending Data From Parent to Child Component (Using Properties):

    • The child component uses @api decorator to expose a property.
    • The parent component sends the data to child component through its HTML file.
    • In below example: 
      • The Data property in the child component is exposed using @api.

      • From the parent component’s HTML file, ‘Hello‘ is sent to the Data property in the child component.

Child Component – HTML

				
					import { api } from 'lwc';

export default class ChildComponent extends LightningElement {
    @api data;  // Receives data from parent
}
				
			

Parent Component – JavaScript

				
					<c-child-component data="Hello"></c-child-component>
				
			

Explore the post below to learn more about @api Decorator in Salesforce LWC

2. Sending Data From Child to Parent Component (Using Custom Events):

    • The ‘child component’ can fire custom event & can send data to the ‘parent component’.
    • The parent component then listens for the event and handles the data.

Child Component – JavaScript

				
					import { LightningElement } from 'lwc';

export default class ChildComponent extends LightningElement {
    handleClick() {
        const event = new CustomEvent('childEvent', { detail: 'Data from Child' });
        this.dispatchEvent(event);  // Sends data to parent
    }
}
				
			

Parent Component – HTML and JavaScript

				
					<c-child-component onchildevent={handleChildData}></c-child-component>
				
			
				
					export default class ParentComponent extends LightningElement {
    handleChildData(event) {
        console.log(event.detail);  // Receives data from child
    }
}
				
			

In Summary:

    • Parent to Child: Use @api in Child Component to expose the property as Public. So that, Parent Component can pass data to the same Child Component’s property.
    • Child to Parent: Use Custom Events from Child Component to Parent Component and send data via events to Parent Component.

Explore the post below to learn more about Custom Events in Salesforce LWC

9. What are the limitations of LWC compared to Aura Components?

1. Browser Support:

LWC requires modern browsers (Chrome, Firefox, etc.) and doesn’t work well with older browsers like Internet Explorer 11, which Aura supports.

2. Limited to Lightning Experience:

LWC is mainly for Salesforce Lightning Experience and doesn’t support Salesforce Classic, while Aura components can work in both Lightning Experience and Classic.

3. No Public Lightning Event Support:

LWC doesn’t support lightning events like Aura components.
LWC uses Custom Events for communication instead, which is more restricted than Aura’s event system.

4. No Application-Level Access:

In LWC, components can’t have the same application-level access as Aura components.

For example, in Aura, you can use application events to communicate globally across the app, but in LWC, communication is more restricted to parent-child relationships.

5. Limited Support for Dynamic Components:

LWC doesn’t provide native support for dynamic component creation (like Aura’s createComponent), which allows dynamically creating components at runtime in Aura.

In Summary

LWC is faster, simpler, and modern, but it has some limitations in terms of browser support, flexibility in communication, and features available in Aura components.

However, LWC is the recommended choice for new development in Salesforce.

10. How does data binding work in LWC?

In Lightning Web Components (LWC), data binding is the connection between the JavaScript controller and the HTML UI Template, ensuring that – changes in one, updates the other.

Please Note:

    • LWC primarily follows one-way data binding, where data flows from the JavaScript class to the HTML template.
    • This means that when you update a property in the JavaScript file, the UI (HTML) automatically reflects the changes.
    • However, you can achieve two-way data binding behaviour by combining one-way binding with event handling.

Types of Data Binding in LWC:

1. One-Way Data Binding:

    • In case of One-Way Binding, data flows from the JavaScript file to the HTML template.
    • It is used for displaying values in the UI. From UI, user cannot update the data.
    • Changes in JavaScript automatically reflect in the UI, but the reverse is not true.

Real Time Use Case of One Way Data Binding:

One Way Data Binding is used in:

    1. Displaying read-only data

    2. Conditional Rendering
    3. Parent to Child Communication
      For Example: A parent component sends a user’s name to a child component for display.

Example:

				
					// MyComponent.js

export default class MyComponent extends LightningElement {
    message = 'Hello, World!';
}
				
			
				
					<!-- myComponent.html -->
<template>
    <p>{message}</p> <!-- Displays 'Hello, World!' -->
</template>
				
			

2. Two-Way Data Binding:

    • Please Note: Two-way data binding is not natively supported in LWC, but it can be achieved by combining one-way binding with event handling
    • In case of Two-Way Binding, data flows both ways between the JavaScript and HTML.
    • Two-Way Binding is achieved using input fields with the value attribute and event handlers.

Real Time Use Case of Two-Way Data Binding:

One Way Data Binding is used in:

    1. User input fields (text, checkbox, etc.)

    2. Search Filters
    3. Interactive UI Changes
    4. Parent – Child Communication with Updates
      Example: A child component (e.g., a search bar) updates a search term, and the parent component uses it to filter data.

Example:

				
					// MyComponent.js

export default class MyComponent extends LightningElement {
    message = 'Hello';

    handleInputChange(event) {
        this.message = event.target.value;  // Updates JavaScript when input changes
    }
}
				
			
				
					<!-- myComponent.html -->

<template>
    <input type="text" value={message} oninput={handleInputChange} />
    <p>{message}</p> <!-- Updates as the input changes -->
</template>
				
			

Summary

    • One-Way Binding: Data flows from JavaScript to the UI (read-only in the UI).
    • Two-Way Binding: Data flows back and forth between the JavaScript and the UI, like when you type in an input box.

11. What are Reactive properties in LWC? How do they function?

In LWC, reactive properties are properties that, when their values change, automatically trigger a re-render of the component to reflect the updated value in the UI.

Reactivity ensures that the component stays in sync with its data.

How Reactive Properties Work:

1. Primitive Properties:

    • Primitive properties (e.g., stringnumberboolean) are reactive by default.
    • When their value changes, the component re-renders to reflect the new value.

    • Example:

Javascript File:

				
					export default class MyComponent extends LightningElement {
    message = 'Hello'; // Reactive by default
}
				
			

HTML File:

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

If message changes, the UI updates automatically.

2. Object and Array Properties:

    • Objects and arrays are not fully reactive by default. To make them reactive, use the @track decorator.

    • Example:

Javascript File:

				
					export default class MyComponent extends LightningElement {
    @track user = { name: 'John', age: 30 }; // Reactive object
}
				
			

HTML File:

				
					<template>
    <p>Name: {user.name}, Age: {user.age}</p>
</template>
				
			

If user.name or user.age changes, the UI updates.

3. Public Properties (@api):

    • Properties marked with @api are reactive and can be passed from a parent component.

    • Example:

Javascript File:

				
					export default class ChildComponent extends LightningElement {
    @api title; // Reactive and public
}
				
			

HTML File:

				
					<!-- Parent HTML -->
<c-child-component title="Welcome"></c-child-component>
				
			

How Do They Function?

  1. Automatic UI Updates:
      • When the value of a reactive property changes, LWC automatically re-renders the part of the UI that uses that property.
  2. No Manual DOM Updates:
      • Developers don’t need to write extra code to update the UI, LWC handles it for you.
  3. How to Declare:
      • Simply define a property in the component’s JavaScript file.
      • If the property is used in the HTML file, it becomes reactive.

Key Points:

    • Primitive properties: Reactive by default.
    • Objects/Arrays: Use @track to make them reactive.

    • Public properties: Use @api for reactivity and parent-child communication.

    • Re-rendering: Changes to reactive properties automatically update the UI.

Reactive properties are a core feature of LWC, making it easy to build dynamic and responsive user interfaces.

12. How do you include CSS in your LWC Component?

You can easily insert CSS in your LWC component, just follow the below steps.

1. Inline CSS in the Component:

    • Create a .css file with the same name as your component.

    • Place it in the same folder as your component.

    • Example:

				
					/* myComponent.css */
.myClass {
    color: red;
    font-size: 16px;
}
				
			
				
					<!-- myComponent.html -->
<template>
    <p class="myClass">Hello, World!</p>
</template>
				
			

2. Scoped CSS:

    • LWC automatically scopes CSS to the component, meaning styles won’t leak out to other components.

    • Example:

				
					/* myComponent.css */
p {
    color: blue; /* This will only apply to <p> tags in this component */
}
				
			

3. Using CSS in HTML:

    • You can directly apply styles using the style attribute in HTML.

    • Example:

				
					<template>
    <p style="color: green; font-size: 20px;">Hello, World!</p>
</template>
				
			

4. Sharing CSS Across Components:

    • Use CSS files in a shared folder and import them into multiple components.

    • Example:

				
					/* sharedStyles.css */
.sharedClass {
    background-color: yellow;
}
				
			
				
					// myComponent.js
import sharedStyles from './sharedStyles.css';
				
			
				
					<!-- myComponent.html -->
<template>
    <p class={sharedStyles.sharedClass}>Shared Style</p>
</template>
				
			

5. Conditional Rendering

    • Use JavaScript to dynamically apply styles based on conditions.

    • Example:

				
					<template>
    <p class={dynamicClass}>Dynamic Style</p>
</template>
				
			
				
					export default class MyComponent extends LightningElement {
    get dynamicClass() {
        return this.isActive ? 'active' : 'inactive';
    }
}
				
			

Key Points:

    • Use a .css file for component-specific styles.
    • CSS is scoped to the component by default.

    • Use shared CSS files for reusable styles.

    • Apply dynamic styles using JavaScript.

This approach ensures clean, modular, and reusable styling in LWC components.

13. What are LifeCycle Hooks in LWC?

Lifecycle hooks in Lightning Web Components (LWC) are special methods that run automatically at different stages of a component’s life (such as – creation, rendering, and removal).
They allow you to execute code at specific points in the component’s lifecycle.

Key Lifecycle Hooks:

1. Constructor

    • Constructor is the first LifeCycle Hook in LWC.
    • It is called when the component is created.
    • It is used to initialize properties / variables or set up the component’s state.

Example:

				
					export default class MyComponent extends LightningElement {
    constructor() {
        super(); // Always call super() first
        console.log('Component created');
    }
}
				
			

2. connectedCallback()

    • connectedCallback() is the 2nd method in the LifeCycle Hook of LWC.
    • conectedCallback() is called when the component is inserted into the DOM.

    • Use it to fetch data, set up event listeners, or initialize the component.

    •  

Example:

				
					connectedCallback() {
    console.log('Component added to the DOM!');
}
				
			

3. renderedCallback()

    • renderedCallback is the 3rd method in LWC LifeCycle hook.
    • Called after the component has rendered or re-rendered.

    • Use it to interact with the DOM after rendering.

Example:

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

4. disconnectedCallback()

    • disconnectedCallback is the 4th method in LWC LifeCycle hook
    • It runs when the component is removed from the DOM.
    • It is used to cleanup tasks, like removing event listeners or timers etc.

Example:

				
					disconnectedCallback() {
    console.log('Component removed from the DOM!');
}
				
			

5. errorCallback(error, stack)

    • Called when an error occurs in a child component.

    • Use it to log errors or display error messages.

    • Example:

				
					errorCallback(error, stack) {
    console.error('Error:', error);
    console.error('Stack:', stack);
}
				
			

Lifecycle Flow:

    1. Creationconstructor() → connectedCallback()

    2. RenderingrenderedCallback()

    3. Updates: Re-renders trigger renderedCallback() again.

    4. DestructiondisconnectedCallback()

In Simple Words:

Lifecycle hooks are methods that let you run specific code when:

    • The component is created (constructor).
    • It is added to the page (connectedCallback).
    • It finishes rendering (renderedCallback).
    • It is removed from the page (disconnectedCallback)
    • Handles errors in child components. (errorCallback)

Explore the post below to learn more about LifeCycle Hooks in Salesforce LWC

14. What is the purpose of connectedCallback() in LWC?

The connectedCallback() method in Lightning Web Components (LWC) runs automatically when the component is added to the DOM (that is – when the component is displayed on the page).

Purpose:

  1. Initialization:
    • Perform setup tasks when the component is added to the DOM.

    • Example: Initialize variables, set default values, or fetch data.

  2. Fetching Data:

    • Call Apex methods or APIs to load data for the component.

    • Example:

				
					connectedCallback() {
    this.loadData();
}

async loadData() {
    const data = await fetchDataFromServer();
    this.data = data;
}
				
			

3. Setting Up Event Listeners:

    • Add event listeners for user interactions or external events.

    • Example:

				
					connectedCallback() {
    window.addEventListener('resize', this.handleResize);
}

handleResize = () => {
    console.log('Window resized');
};
				
			

4. DOM Manipulation:

    • Access or manipulate the DOM after the component is added.

    • Example:

				
					connectedCallback() {
    const element = this.template.querySelector('div');
    element.classList.add('active');
}
				
			

5. Subscribing to Pub/Sub Events:

    • Subscribe to Lightning Message Service or other event systems.

    • Example:

				
					connectedCallback() {
    this.subscription = subscribeToMessageChannel(this.handleMessage);
}
				
			

In Simple Words

  1. When it runs: When the component is added to the DOM.
    The code written inside connectedCallback() runs automatically when the component appears on the screen.
  2. Use cases:

    • Fetching data.

    • Setting up event listeners.

    • Initializing the component.

    • Subscribing to events.

  3. Cleanup: Use disconnectedCallback() to undo any setup (e.g., remove event listeners).

Explore the post below to learn more about the Role and Properties of connectedCallback() in Salesforce LWC

15. What is the significance of 'renderedCallback()' in LWC?

The renderedCallback() lifecycle hook in LWC is called after the component has rendered or re-rendered. It is useful for performing actions that depend on the component’s DOM being fully rendered. Here’s its significance and common use cases:

Significance

renderedCallback() is used to perform actions that need to happen after the UI is fully loaded, like:

  1. DOM Interaction:

    • Access or manipulate the DOM after it has been rendered.

    • Example: Add classes, set attributes, or initialize third-party libraries (e.g., charts, maps).

  2. Conditional Logic Based on Rendering:

    • Perform actions only after the component has rendered.

    • Example: Scroll to a specific element or focus on an input field.

  3. Avoiding Infinite Loops:

    • Be cautious when modifying reactive properties or the DOM inside renderedCallback(), as it can trigger re-renders and create infinite loops.

Common Use Cases:

1. DOM Manipulation:

				
					renderedCallback() {
    const button = this.template.querySelector('button');
    if (button) {
        button.classList.add('active');
    }
}
				
			

2. Initializing Third-Party Libraries:

				
					renderedCallback() {
    const chartElement = this.template.querySelector('.chart');
    if (chartElement && !this.chartInitialized) {
        this.initializeChart(chartElement);
        this.chartInitialized = true;
    }
}
				
			

3. Focusing on an Input Field:

				
					renderedCallback() {
    const inputField = this.template.querySelector('lightning-input');
    if (inputField) {
        inputField.focus();
    }
}
				
			

4. Conditional Rendering Checks:

				
					renderedCallback() {
    if (this.showDetails) {
        const detailsSection = this.template.querySelector('.details');
        detailsSection.scrollIntoView();
    }
}
				
			

Important points:

    • When it runs: After the component is rendered or re-rendered.

    • Use cases:

      • DOM manipulation.

      • Initializing third-party libraries.

      • Focusing on elements or scrolling.

    • Avoid infinite loops: Be careful not to modify reactive properties or the DOM in a way that triggers re-renders unnecessarily.

      • It may run multiple times if the component re-renders (e.g., when reactive properties change).
      • To avoid running code repeatedly, use a flag to check if the logic has already been executed.

Example

				
					import { LightningElement } from 'lwc';

export default class MyComponent extends LightningElement {
    renderedCallback() {
        console.log('Component rendered');
        const element = this.template.querySelector('div');
        if (element) {
            element.classList.add('highlight');
        }
    }
}
				
			

In Simple Words:

In summary, renderedCallback() is used to interact with the DOM or perform actions after the component has rendered, ensuring the DOM is fully available for manipulation.

Explore the post below to learn more about the Role and Properties of renderedCallback() in Salesforce LWC

16. How can you use JavaScript modules in LWC?

In LWC, JavaScript modules allow you to organize and reuse code by splitting it into separate files. You can use import and export statements to share functions, variables, or classes between files.

Here’s how you can use JavaScript modules in LWC:

Steps to Use JavaScript Modules in LWC:

1. Create a JavaScript Module:

    • Create a .js file to define reusable functions, constants, or classes.
    • Place it in the modules folder (custom modules) or utils folder (utility code).
    • Use export to expose functions, variables, or classes.

Example (utils.js):

				
					export function add(a, b) {
    return a + b;
}
				
			

2. Export the Code:

    • Use the export keyword to make functions, variables, or classes available for other files.

3. Import the Module in LWC:

    • Use the import keyword to use the module in your component’s JavaScript file.

Example (Importing utils.js in LWC):

				
					import { add } from './utils.js';

export default class MyComponent extends LightningElement {
    result = add(2, 3);  // Uses the imported function
}
				
			

Benefits

    • Keeps code organized and reusable.
    • Reduces duplication by centralizing shared logic.

In Simple Words:

    • Use export to expose functionality in a module.

    • Use import to bring functionality into your component.

    • Modules promote code reusability and organization.

    • Supports both named exports and default exports.

17. What are decorators in LWC? Why they are used?

Decorators in Lightning Web Components (LWC) are special keywords (like @api, @track, and @wire) used to add specific functionality to JavaScript properties or methods.

Why Decorators are used?

Decorators in LWC define – how a property or method should behave in the LWC framework. They help in:

    1. Exposing Data to Other Components: Using @api.
    2. Making Properties Reactive: Using @track.
    3. Connecting to Salesforce Data: Using @wire.

Common Decorators

1. @api

    • Exposes properties or methods of Child LWC Component to its Parent LWC Components.

Example:

				
					export default class MyComponent extends LightningElement {
    @api message = 'Hello, World!'; // Public property
}
				
			

2. @track

    • Makes an object or array property reactive, so UI updates automatically when the property changes.
    • Changes to the property trigger a re-render.

Example:

				
					export default class MyComponent extends LightningElement {
    @track user = { name: 'John', age: 30 }; // Reactive object
}
				
			

3. @wire

    • Automatically fetches data from Salesforce (like Apex methods or wire adapters).

Example:

				
					import { LightningElement, wire } from 'lwc';
import getContactList from '@salesforce/apex/ContactController.getContactList';

export default class MyComponent extends LightningElement {
    @wire(getContactList) contacts; // Wire to Apex method
}
				
			

Why Decorators Are Used:

    1. Simplify Code:

      • Decorators reduce boilerplate code by adding functionality declaratively.

      • Example: @api eliminates the need for manual getters/setters to expose properties.

    2. Reactivity:

      • Decorators like @track and @api make properties reactive, ensuring the UI updates automatically when data changes.

    3. Data Binding:

      • Decorators like @wire enable easy data binding to Salesforce data sources (e.g., Apex methods, Lightning Data Service).

    4. Component Communication:

      • Decorators like @api facilitate communication between parent and child components.

    5. Metadata:

      • Decorators add metadata to properties or methods, defining their behavior in the framework.

Explore the post below to explore more about 3 decorators in Salesforce LWC – @api, @track, @wire

Example: Using Decorators:

				
					import { LightningElement, api, track, wire } from 'lwc';
import getAccountList from '@salesforce/apex/AccountController.getAccountList';

export default class MyComponent extends LightningElement {
    @api title = 'Account List'; // Public property
    @track accounts = []; // Reactive property
    @wire(getAccountList) wiredAccounts({ data, error }) {
        if (data) {
            this.accounts = data;
        } else if (error) {
            console.error(error);
        }
    }
}
				
			
				
					<template>
    <h1>{title}</h1>
    <ul>
        <template for:each={accounts} for:item="account">
            <li key={account.Id}>{account.Name}</li>
        </template>
    </ul>
</template>
				
			

Key Points:

    1. Decorators are prefixed with @ (e.g., @api@track@wire).

    2. They simplify code, enable reactivity, and facilitate component communication.

    3. Commonly used for:

      • Exposing properties/methods (@api).

      • Making properties reactive (@track).

      • Binding to data sources (@wire).

Decorators are a powerful feature in LWC that enhance component functionality and maintainability.

18. How do you bind events in LWC?

In LWC, event binding allows you to handle user interactions (e.g., clicks, input changes) or custom events. You can bind events to methods in your component’s JavaScript class using the on prefix in the HTML template.

In LWC, you link events like – a button click from the HTML file to a Method in the JavaScript file.

Steps to Bind Events:

1. Define the Event in HTML:

    • In the HTML file, use the on prefix followed by the event name (e.g., onclickonchange) to bind the event to the method.
    • Then specify the JavaScript method (for example: handleClick) to call in the same HTML file.

Example:

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

2. Create the Method in JavaScript:

    • Define the same method (handleClick) in the component’s .js file.

Example:

				
					export default class MyComponent extends LightningElement {
    handleClick() {
        console.log('Button clicked!');
    }
}
				
			

3. Access Event Data (Optional):

    • Use the event parameter to get details like the value of an input or the event type.

Example:

				
					handleInput(event) {
    console.log(event.target.value);  // Logs the input's value
}
				
			
				
					<input type="text" oninput={handleInput} />
				
			

Common Event Bindings:

1. Click Event:

				
					<template>
    <button onclick={handleClick}>Click Me</button>
</template>
				
			
				
					export default class MyComponent extends LightningElement {
    handleClick() {
        console.log('Button clicked');
    }
}
				
			

2. Input Change Event:

				
					<template>
    <lightning-input label="Name" onchange={handleInputChange}></lightning-input>
</template>
				
			
				
					export default class MyComponent extends LightningElement {
    handleInputChange(event) {
        console.log('Input value:', event.target.value);
    }
}
				
			

3. Custom Event:

				
					<template>
    <c-child oncustomEvent={handleCustomEvent}></c-child>
</template>
				
			
				
					export default class MyComponent extends LightningElement {
    handleCustomEvent(event) {
        console.log('Custom event data:', event.detail);
    }
}
				
			

Key Points:

    • Use the on prefix to bind events in the HTML template (e.g., onclickonchange).

    • Define event handler methods in the JavaScript class.

    • Access event details using the event object (e.g., event.target.value for input changes).

19. What is the purpose of template.querySelector in LWC?

The template.querySelector method in Lightning Web Components (LWC) is used to find and access a specific HTML element in the component’s template.

Purpose

    • To interact with an element directly, like changing its value, style, or attributes.
    • It selects the first matching element based on the provided CSS selector.

Example:

				
					handleClick() {
    const inputElement = this.template.querySelector('input');
    inputElement.value = 'Updated Value';  // Changes the input's value
}
				
			

Key Points:

    • template.querySelector is used to access elements in the component’s shadow DOM.
    • Use CSS selectors to find specific elements.

    • Commonly used for DOM manipulation, event handling, and conditional logic.

    • Avoid overusing it; prefer declarative data binding when possible.

Example:

				
					<template>
    <div class="myDiv">Hello</div>
    <button>Click Me</button>
</template>
				
			
				
					import { LightningElement } from 'lwc';

export default class MyComponent extends LightningElement {
    renderedCallback() {
        const div = this.template.querySelector('.myDiv');
        div.style.color = 'blue';

        const button = this.template.querySelector('button');
        button.addEventListener('click', this.handleClick);
    }

    handleClick() {
        console.log('Button clicked');
    }
}
				
			

20. What is the difference between 'template.querySelector' and 'template.querySelectorAll' in LWC?

In LWC, both template.querySelector and template.querySelectorAll are used to access DOM elements within the component’s template, but they serve different purposes:

1. template.querySelector:

    • Purpose: Selects the first matching element in the template.

    • Return Value: A single DOM element (or null if no match is found).

    • Use Case: When you need to interact with a single element.

    • Example:

				
					const button = this.template.querySelector('button');
button.classList.add('active');
				
			

2. template.querySelectorAll:

    • Purpose: Selects all matching elements in the template.

    • Return Value: A NodeList (array-like collection of elements).

    • Use Case: When you need to interact with multiple elements.

    • Example:

				
					const buttons = this.template.querySelectorAll('button');
buttons.forEach(button => {
    button.classList.add('active');
});
				
			

Key Differences:

Featuretemplate.querySelectortemplate.querySelectorAll
Returns  Single element (or null)NodeList (collection of elements)
Use Case.     Accessing a single elementAccessing multiple elements
Example.  this.template.querySelector('div')this.template.querySelectorAll('div')

Example:

				
					<template>
    <div class="item">Item 1</div>
    <div class="item">Item 2</div>
    <div class="item">Item 3</div>
</template>
				
			
				
					import { LightningElement } from 'lwc';

export default class MyComponent extends LightningElement {
    renderedCallback() {
        // Select the first matching element
        const firstItem = this.template.querySelector('.item');
        console.log('First Item:', firstItem.textContent); // Output: "Item 1"

        // Select all matching elements
        const allItems = this.template.querySelectorAll('.item');
        allItems.forEach(item => {
            console.log('Item:', item.textContent); // Output: "Item 1", "Item 2", "Item 3"
        });
    }
}
				
			

In Simple Words

    • Use template.qyerySelector when you need to interact with a single element.

    • Use template.querySelectorAll when you need to interact with multiple elements.

Conclusion

Congratulations! You’ve just explored the first set of 20 LWC interview questions and answers. These questions cover essential topics like reactive properties, lifecycle hooks, event handling, and DOM manipulation, which are crucial for any LWC developer.

Stay tuned for the next blog post, where we’ll dive into 20 more LWC interview questions to further enhance your skills and confidence. 
Happy learning, and best of luck with your interviews!

Share This Article
Follow:
Chinmaya is working as a Senior Consultant with a deep expertise in Salesforce. Holding multiple Salesforce certifications, he is dedicated to designing and implementing cutting-edge CRM solutions. As the creator of Writtee.com, Chinmaya shares his knowledge on educational and technological topics, helping others excel in Salesforce and related domains.
1 Comment