Understanding Decorators and Lifecycle Hooks in Salesforce LWC
Understand LWC decorators (@api, @track, @wire) and lifecycle hooks with clear examples — what each does and when to use it in your components.
The JavaScript concepts to know before starting Lightning Web Components — variables, functions, objects, arrays, classes, modules and promises.
JavaScript is the powerhouse behind Lightning Web Components (LWC) development in Salesforce. It's like the fuel that drives your car – without it, you won't get far! In this blog, we'll break down JavaScript essentials in a simple and easy-to-understand manner, so you can turbocharge your LWC skills and propel your Salesforce journey to new heights. Let's dive in!
Get ready to dive deep into the core concepts of JavaScript, essential for mastering Lightning Web Components! We'll walk you through everything from understanding how to declare variables with var, let, and const, to utilizing powerful tools like the spread operator and de-structuring. You'll also learn about string interpolation, array functions, promises, arrow functions, and event handling, all explained with simple examples to help you level up your LWC development skills. Let's get started!
var
var is used for variable declaration in JavaScript. It has a function-level scope, meaning it is visible within the function in which it is defined or globally if defined outside any function.var can be redeclared and reassigned.Example:
function varExample() {
var x = 10;
if (true) {
var x = 20;
console.log(x); // Output: 20
}
console.log(x); // Output: 20
}
varExample();
console.log(x); // Throws ReferenceError: x is not defined
Explanation:
if block, the value of x is reassigned to 20.x retains its new value of 20, as var doesn't have block scope.x is not accessible.Mind it!
1. It can be updated and re-declare
var myName = "Saurabh"
console.log(myName) // Output: Saurabh
var myName = "Saurabh Samir"
console.log(myName) // Output: Saurabh Samir
2. Automatically bind with window property if its not inside any block or function
var bind = 'Lightning Web Components!'
console.log(window.bind) // Output: Lightning Web Components!
3. It support on function scope or global scope
function myFunScope(){
var varFunScope = 'Var Function Scope'
console.log(varFunScope)
}
myFunScope()
console.log(varFunScope) //---> (will give you an error)
4. Does no Support Block level scope
if(true){
var blkScope = 'Var Block Scope'
console.log(blkScope)
}
console.log(blkScope)
/* output:- Var Block Scope
Var Block Scope */
let:
let was introduced in ES6 and has a block-level scope, meaning it is only visible within the block in which it is defined.let can be reassigned, but not redeclared within the same scope.Example:
function letExample() {
let y = 10;
if (true) {
let y = 20;
console.log(y); // Output: 20
}
console.log(y); // Output: 10
}
letExample();
console.log(y); // Throws ReferenceError: y is not defined
Explanation:
if block, a new variable y is declared with a value of 20, scoped to the block.y retains its original value of 10.Mind it!
1. It can be updated but cannot re-declared
let myName = "Saurabh"
console.log(myName)
let myName = "Saurabh Samir"
console.log(myName) // SyntaxError: 'myName' has already been declared
2. let support function and block level scope
function myLetFunScope(){
let letFunScope = 'let Function Scope'
console.log(letFunScope)
}
myLetFunScope()
//console.log(letFunScope) //---> (will give you an error)
3. It support global level scope but does not create property on global object
let myScope = 'window scope'
console.log(window.myScope) // will give you undefined
const
const is used for constant declaration in JavaScript. It also has block-level scope like let.const cannot be reassigned or redeclared.Example:
function constExample() {
const z = 10;
if (true) {
const z = 20; // Throws SyntaxError: Identifier 'z' has already been declared
}
console.log(z); // Output: 10
}
constExample();
Explanation:
z inside the block throws a SyntaxError.z retains its original value of 10.Mind it!
1. It cannot be updated also cannot re-declared
const name = 'Saurabh'
name = 'Saurabh Samir'
console.log(name) // will give you an error
2. Support function and block level scope
function myLetFunScope(){
const letFunScope = 'const Function Scope'
console.log(letFunScope)
}
myLetFunScope()
//console.log(letFunScope) //---> (will give you an error)
3. It support global level scope but does not create property on global object
const a = 'a'
console.log(this.a) // undefined
Understanding the differences and appropriate use of var, let, and const is crucial for effective LWC development, ensuring code clarity, maintainability, and avoiding unexpected behavior.
The spread operator (...) in JavaScript allows you to expand an iterable (like an array or string) into individual elements. It's particularly useful for copying arrays, combining arrays, or passing multiple arguments to a function.
Let's explore it with an example:
1. Copying an array
// Example 1: Copying an array
const originalArray = [1, 2, 3, 4, 5];
const copiedArray = [...originalArray];
console.log(copiedArray); // Output: [1, 2, 3, 4, 5]
In this example, the spread operator ...originalArray copies all elements from originalArray into copiedArray.
2. Combining Arrays : add value to array
// Example 2: Combining arrays
const array1 = [1, 2, 3];
const array2 = [4, 5, 6];
const combinedArray = [...array1, ...array2];
console.log(combinedArray); // Output: [1, 2, 3, 4, 5, 6]
Here, the spread operator is used to concatenate array1 and array2 into combinedArray.
// Example 3: Passing multiple arguments to a function
function sum(a, b, c) {
return a + b + c;
}
const numbers = [1, 2, 3];
const result = sum(...numbers);
console.log(result); // Output: 6
In this example, the spread operator ...numbers passes individual elements of the numbers array as arguments to the sum function.
4. Combining Object : add value to Object
If left and right side spread operator has same property the right one will override it
var obj1 = {
firstName: 'Saurabh',
age: 28
}
var obj2 = {
firstName: 'Saurabh SFDC',
age: 29,
sex: 'Male'
}
var objectSpread = {...obj1, ...obj2}
console. log(objectSpread)
/* Output :-
{firstName: 'Saurabh SFDC', age: 29, sex: 'Male'}
* /
Using spread operator, the previous value of array will not be affected if you push
var arr = ['saurabh', 'samir']
var shallowCopy = [...arr]
shallowCopy.push('SFDC' )
console.log(arr)
console.log(shallowCopy)
/* Output :-
['saurabh', 'samir']
['saurabh', 'samir', 'SFDC'] */
Mind it!
The spread operator is a versatile tool that simplifies array manipulation and function calls in JavaScript, making it a valuable asset for Lightning Web Components developers.
Destructuring assignment in JavaScript allows you to extract values from arrays or properties from objects and assign them to variables. It provides a concise way to unpack values from data structures.
Let's explore it with examples:
1. Array Destructuring
// Example 1: Destructuring an array
const numbers = [1, 2, 3];
const [a, b, c] = numbers;
console.log(a); // Output: 1
console.log(b); // Output: 2
console.log(c); // Output: 3
In this example, the values of the numbers array are destructured into individual variables a, b, and c.
2. Object Destructuring
// Example 2: Destructuring an object
const person = { name: 'Saurabh', age: 30 };
const { name, age } = person;
console.log(name); // Output: Saurabh
console.log(age); // Output: 30
Here, the properties name and age of the person object are extracted and assigned to variables with the same names.
3. Default Values
// Example 3: Using default values in destructuring
const numbers = [1, 2];
const [a, b, c = 3] = numbers;
console.log(a); // Output: 1
console.log(b); // Output: 2
console.log(c); // Output: 3 (default value)
In this case, if there's no corresponding element in the array for c, it will default to 3.
4. Nested Destructuring
// Example 4: Nested destructuring
const person = { name: 'Samir', age: 30, address: { city: 'New York', country: 'USA' } };
const { name, age, address: { city, country } } = person;
console.log(city); // Output: New York
console.log(country); // Output: USA
This example demonstrates how to destructure nested objects.
Destructuring provides a concise and powerful way to work with arrays and objects in JavaScript, making code more readable and maintainable, which is beneficial for Lightning Web Components developers.
String interpolation, also known as template literals, is a feature in JavaScript that allows you to embed expressions into strings. It provides a more readable and convenient way to concatenate strings and variables.
Let's explore it with an example:
// Example: String interpolation
const name = 'Samir';
const age = 30;
const message = `Hello, my name is ${name} and I am ${age} years old.`;
console.log(message); // Output: Hello, my name is Samir and I am 30 years old.
In this example, the ${} syntax is used to embed variables name and age within the string. When the message variable is logged to the console, it displays the interpolated string with the values of name and age dynamically inserted.
Let's explore it with an another example:
// Example: String interpolation
var num1 = 10
var num2 = 10
console.log(`Sum of ${num1} & ${num2} is ${num1+num2}`)
var url = "https: //www.learnfrenzy.com"
console.log(`click here ${url}`)
/* Output :-
Sum of 10 & 10 is 20
click here https://www.learnfrenzy.com */
String interpolation is particularly useful in Lightning Web Components development when generating dynamic text for components or displaying data retrieved from Salesforce records. It offers a cleaner and more efficient way to construct strings, enhancing the readability and maintainability of your code.
Array functions in JavaScript provide convenient methods for manipulating arrays, such as iterating over elements, filtering, mapping, and reducing. They offer a more concise and readable way to perform common operations on arrays.
syntax :
arr.methodName(function(currentItem, index, array){
//return something
})
Let's explore some examples:
1. map() method creates a new array with the results of calling a function for every array element.
// Example: Map function
var arr = [1,3,2,4,5]
let multipleOfTwo = arr.map(function(currentItem, index, array){
console.log(`current item ${currentItem} index ${index} array ${array}`)
return currentItem*10;
})
console.log(arr);
console.log('map() value of arr:'+multipleOfTwo)
/* Output : -
current item 1 index 0 array 1,3,2,4,5 current item 3 index 1 array 1,3,2,4,5 current item 2 index 2 array 1,3,2,4,5 current item 4 index 3 array 1,3,2,4,5 current item 5 index 4 array 1,3,2,4,5
(5) [1, 3, 2, 4, 5]
map() value of arr: - 10,30,20,40,50 */
In this example, the map function applies a transformation to each element of the numbers array, 10 times each number.
2. every() return true or false if every statement satisfied condition
// Example: every() function
var arr = [1,2,3,4,5]
let arrEvery = arr.every(function (currentItem){
return currentItem >=2
})
console.log('every() function value:'+arrEvery); //false
3. some() return true if at least one array item satisfied condition
// Example: some() function
var arr = [1,2,3,4,5]
let arrSome = arr.some(function (currentItem){
return currentItem >2
})
console.log('some() function value:'+arrSome); //true
4. filter() return new array with filtered value
// Example: Filter function
var arr = [1,3,2,4,5]
let arrFilter = arr.filter(function (currentItem){
return currentItem >3
})
console.log('filter() function value:'+arrFilter); // Output: 4,5
Here, the filter function creates a new array containing only the greater than 3 numbers from the numbers array.
5. reduce() this function reduce array to a single value
syntax:
arr.reduce(function(total, currentItem, index, array){
return something
}, initialValue)
whatever is your initial value is that would be in total value
// Example: Reduce function
var arr = [1,3,2,4,5]
let arrReduce = arr.filter(function (total,currentItem){
return total+currentItem
},0)
console.log('reduce() function for totaling:'+arrReduce); // Output: 15
The reduce function iterates over the elements of the array, accumulating a single value (in this case, the sum of all numbers).
6. sort() used to sort elements in desc or asc
// Example: sort() function
var arr = [1,3,2,4,5]
let arrSort = arr.sort(function(first,last){
return last-first
})
console.log('Sort in Descending order: ' + arrSort);
console.log('Sort in Accending order: ' + arr.sort());
/* Output:
Sort in Descending order: 5,4,3,2,1
Sort in Accending order: 1,2,3,4,5
*/
Mind it!
Array functions are powerful tools for LWC developers, enabling efficient manipulation of data arrays within Lightning components. They help streamline code, improve readability, and enhance productivity when working with arrays.
Promises in JavaScript are used to handle asynchronous operations. They represent a value that may be available now, or in the future, or never. Promises provide a cleaner alternative to callback functions for handling asynchronous code. Let's explore an example:
// Example: Using Promise for asynchronous operation
function fetchData() {
return new Promise((resolve, reject) => {
// Simulate fetching data asynchronously
setTimeout(() => {
const data = ['apple', 'banana', 'orange'];
if (data.length > 0) {
resolve(data); // Resolve the promise with data
} else {
reject('No data found'); // Reject the promise with an error message
}
}, 2000); // Simulate a delay of 2 seconds
});
}
// Call the fetchData function
fetchData()
.then(data => {
console.log('Data fetched successfully:', data);
})
.catch(error => {
console.error('Error fetching data:', error);
});
In this example:
fetchData function that returns a promise. Inside the promise executor function, we simulate fetching data asynchronously using setTimeout.data.length > 0), we call the resolve function with the fetched data.reject function with an error message.fetchData function and chain a .then method to handle the resolved promise (successful case) and a .catch method to handle the rejected promise (error case).Output:
Data fetched successfully: ['apple', 'banana', 'orange']
Promises are commonly used in Lightning Web Components development for handling asynchronous operations such as fetching data from Salesforce using Apex methods, making HTTP requests to external APIs, or performing other asynchronous tasks. They provide a structured and readable way to manage asynchronous code flow and handle both success and error cases.
Arrow functions, introduced in ECMAScript 6 (ES6), provide a more concise syntax for writing JavaScript functions. They are especially useful for defining inline functions or when using function expressions. Let's explore an example:
// Example: Arrow function
const add = (a, b) => {
return a + b;
};
console.log(add(5, 3)); // Output: 8
In this example:
add that takes two parameters a and b.=>) separates the parameters from the function body.return a + b;.return statement when the function body is a single expression.Output:
Arrow functions are concise and easy to read, making them a preferred choice for defining functions in Lightning Web Components development. They are commonly used for event handlers, callback functions, and when passing functions as arguments to other functions.
Event Handler
Event handlers in Lightning Web Components (LWC) are methods defined in a component's JavaScript file to handle user interactions or system events triggered by the component. These event handlers are bound to HTML elements or custom events and are executed when the corresponding event occurs.
Mind it!
when we provide event in HTML, event always begin with “on” eg onClick, onChange etc. It has predefined event available in HTML
Let's explore an example:
<template>
<lightning-card title="Event Handler Example">
<div class="slds-p-around_medium">
<lightning-button label="Click Me" onclick={handleButtonClick}></lightning-button>
</div>
</lightning-card>
</template>
// exampleComponent.js
import { LightningElement } from 'lwc';
export default class ExampleComponent extends LightningElement {
handleButtonClick() {
// Handle button click event
console.log('Button clicked!');
}
}
In this example:
handleButtonClick() method is an event handler defined in the ExampleComponent class. It is responsible for handling the click event when the button is clicked.onclick attribute in the HTML template binds the handleButtonClick() method to the click event of the lightning-button element.handleButtonClick() method is invoked, and the message "Button clicked!" is logged to the console.Output:
This demonstrates how event handlers are used in LWC to respond to user interactions, such as button clicks. Event handlers play a vital role in building interactive and responsive user interfaces in Lightning Web Components.
Event Listener
In Lightning Web Components (LWC), event listeners are used to listen for and handle events dispatched by other components or system events. These listeners are defined using the addEventListener() method, which attaches a callback function to be executed when a specific event occurs.
In Event Listener, we have two methods
Let's explore an example:
<template>
<lightning-card title="Event Handlers Example">
<div class="slds-p-around_medium">
<p>Click anywhere in the document to trigger the event</p>
</div>
</lightning-card>
</template>
// exampleComponent.js
import { LightningElement, track } from 'lwc';
export default class ExampleComponent extends LightningElement {
connectedCallback() {
// Adding an event listener to listen for click event on the document
document.addEventListener('click', this.handleDocumentClick);
}
disconnectedCallback() {
// Removing the event listener when the component is disconnected
document.removeEventListener('click', this.handleDocumentClick);
}
handleDocumentClick(event) {
// Handling the document click event
console.log('Document clicked!', event.target);
}
}
In this example:
connectedCallback() lifecycle hook, an event listener is added to the document to listen for the click event using addEventListener(). The handleDocumentClick() method is specified as the callback function to be executed when the click event occurs.disconnectedCallback() lifecycle hook, the event listener is removed using removeEventListener() when the component is disconnected from the DOM.handleDocumentClick() method is invoked, and the message "Document clicked!" along with the target element that triggered the event is logged to the console.Output (upon clicking anywhere in the document):
This demonstrates how event listeners are used in LWC to listen for and respond to events occurring outside the component, such as document-level events. Event listeners provide a powerful mechanism for handling various events and interactions in Lightning Web Components.
Custom Event
You can create custom event with the help of CustomeEvent constructor
After creating Custom Event, we need to dispatch event with help of dispatchEvent() method.
Once dispatching event done, we have to handle a listener, so we have to add addEventListener() method.
Let's explore an example:
<html>
<head>
<title>LWC Learning</title>
</head>
<script src="./index.js"></script>
<body>
<button onclick="callCustomEvent()">Custom Event</button>
</body>
</html>
function callCustomEvent(){
let myEvent = new CustomEvent('myEventName',{
detail: {myName: 'Saurabh Samir'}
})
document.dispatchEvent(myEvent)
}
document.addEventListener("myEventName", function(data){
console.log(data.detail);
})
“Stay tuned for more exciting LWC topics, and keep exploring the world of Lightning Web Components to become a Salesforce development pro.”
Happy coding with LWC!
One short email when we publish something new — interview questions, Salesforce guides and career tips. No spam, unsubscribe in one click.
Understand LWC decorators (@api, @track, @wire) and lifecycle hooks with clear examples — what each does and when to use it in your components.
JavaScript fundamentals for Lightning Web Components — scope, this, closures, promises, events and modules — explained with LWC-focused examples.
Lightning Web Components basics — component files, HTML templates, JavaScript class, decorators and data binding — explained for beginners.
Questions, corrections or your own experience — they all help the next reader.