Prior knowledge of JS for LWC

Saurabh Samir
8 min readMar 10, 2024

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, Let & const keywords
  • Spread Operator
  • De-structuring
  • String Interpolation
  • Array Functions
  • Use of Promise
  • Arrow Function
  • Event

Var, Let & const keywords

`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.
  • Variables declared with `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:

  • Inside the `if` block, the value of `x` is reassigned to 20.
  • After the block, `x` retains its new value of 20, as `var` doesn’t have block scope.
  • Outside the function, `x` is not accessible.

MIND IT !

var keyword

  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.
  • Variables declared with `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:

  • Inside the `if` block, a new variable `y` is declared with a value of 20, scoped to the block.
  • Outside the block, `y` retains its original value of 10.

MIND IT !

let keyword

  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

Output:

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)

Output:

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

Output:

`const`:

  • `const` is used for constant declaration in JavaScript. It also has block-level scope like `let`.
  • Variables declared with `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:

  • Attempting to redeclare `z` inside the block throws a SyntaxError.
  • Outside the block, `z` retains its original value of 10.

MIND IT !

const keyword

  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)

Output:

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.

Spread (…) Operator

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]

Output:

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]

Output:

Here, the spread operator is used to concatenate `array1` and `array2` into `combinedArray`.

3. Passing multiple arguments to a function

// 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'}
* /

5. Creating new shallow copy of Array and object

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'] */

Output:

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.

De-structuring

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

Output:

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

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 */

Output:

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.

For More briefly visit the link below:

“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!

--

--

Saurabh Samir

Engineer @Accenture | Salesforce Developer | Full Stack Developer