Understanding Variables in LWC: var, let, and const

Variables in LWC JavaScript
Chinmaya By Chinmaya
5 Min Read

Introduction

Lightning Web Components (LWC) uses JavaScript as its core programming language, and working with variables is an essential part of writing JavaScript code.

In this blog post, we will explore the three main ways to declare variables in JavaScript (var, let, and const) and understand their usage with examples in the context of LWC.

1. var - Function Scoped Variables

The ‘var’ keyword has been around since the early days of JavaScript.

Variables declared with var are function-scoped, meaning they are accessible throughout the function in which they are defined, even before they are declared (due to hoisting).

				
					import { LightningElement } from 'lwc';

export default class VarExample extends LightningElement {
    connectedCallback() {
        console.log(myVar); // Outputs: undefined (hoisted but not assigned yet)
        var myVar = 'Hello from var!';
        console.log(myVar); // Outputs: Hello from var!
    }
}
				
			

Key Points:

    • Variables declared with var are hoisted to the top of the function.
    • It can lead to bugs due to unexpected behavior in larger applications.
    • It is not block-scoped, meaning it ignores curly braces { }.

2. let - Block Scoped Variables

The ‘let’ keyword is a modern way to declare variables in JavaScript.

It is block-scoped, meaning the variable is only accessible within the { } block where it is defined.

				
					import { LightningElement } from 'lwc';

export default class LetExample extends LightningElement {
    connectedCallback() {
        let message = 'Hello from let!';
        console.log(message); // Outputs: Hello from let!

        if (true) {
            let message = 'Scoped within if block';
            console.log(message); // Outputs: Scoped within if block
        }

        console.log(message); // Outputs: Hello from let!
    }
}   
				
			

Key Points:

    • ‘let’ is not hoisted, so you must declare it before use.
    • It is block-scoped, so it respects the boundaries of { }.
    • Use let, when you need to update the variable value later in the code.

3. const - Constants

The ‘const’ keyword is used to declare variables that should not be reassigned.
Like let, it is block-scoped, but once a value is assigned, it cannot be changed.

				
					import { LightningElement } from 'lwc';

export default class ConstExample extends LightningElement {
    connectedCallback() {
        const greeting = 'Hello from const!';
        console.log(greeting); // Outputs: Hello from const!

        // Uncommenting the line below will cause an error
        // greeting = 'Cannot reassign const variable';
    }
}
				
			

Key Points:

    • Must be initialized at the time of declaration.
    • Cannot be reassigned, but if the value is an object or array, its properties can be modified.
    • Use ‘const’ when the value should remain constant throughout the program.

When to Use - 'var', 'let', and 'const' in LWC?

    • Avoid var in modern JavaScript development as it can lead to bugs due to hoisting and lack of block scoping.
    • Use let for variables that may change values, such as counters, flags, or temporary data.
    • Use const for variables that should not be reassigned, such as configuration settings, DOM selectors, or constants.

Practical Example in LWC

variableDemo.js

				
					import { LightningElement, track } from 'lwc';

export default class VariableDemo extends LightningElement {
    @track message = 'Welcome to LWC!';

    connectedCallback() {
        const appName = 'LWC App';
        let counter = 0;

        for (let i = 0; i < 3; i++) {
            counter += 1;
            console.log(`Iteration ${i}: Counter = ${counter}`);
        }

        console.log(`App Name: ${appName}`);
        console.log(`Final Counter: ${counter}`);
    }
}
				
			

variableDemo.html

				
					<template>
    <h1 id="message" class="rb-heading-index-11">{message}</h1>
</template>
				
			

Output

    • Iteration logs show the counter updates due to let.
    • The appName declared with const remains unchanged.

Conclusion

Understanding the difference between var, let, and const is crucial for writing clean, bug-free code in LWC. By using let and const appropriately, you can create scalable and maintainable components. So, remember:

    • Use const for constants.
    • Use let for reassignable variables.
    • Avoid var for modern, robust development.

Happy coding! 🎉

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.
Leave a comment