ES6 Javascript Tips for Lightning Web Component Developers
Variables
ES6 introduced let and const keywords for defining variables.
- let:
Allows to declare a variable with block scope.
Eg:
This will throw an error saying ‘x is not defined’ since variable is defined inside brackets.
{
let x = 2;
}
console.log(x);
- const:
Allows to declare a constant variable which cannot reassign values. But, the properties of constant object can be updated.. Also, const variables are block scoped.
Eg:
This will throw an error.
const y = 5;
y = 10;
String Interpolation
String interpolation using Template literals allow embedded expressions. These template literals are enclosed by the backtick (` `) character instead of double or single quotes.
Eg:
var name = "John";
console.log(`Hello, ${name}!`);
Object Initialization
When defining an object with keys have the same name as the variables passed-in as properties, you can use the shorthand and simply pass the key name.
Eg:
Following object can be defined with shorter notation in ES6.
let o = {
a: a,
b: b,
c: c
}
to
let o = {a, b, c}
Arrow functions
An arrow functions introduced as compact alternative to a regular function expression.
hello = function() {
return "Hello World!";
}
to
hello = () => {
return "Hello World!";
}
Default parameters
This allow named parameters to be initialized with default values if no value or undefined is passed.
function multiply(a, b = 1) {
return a * b;
}
Destructing objects / arrays
The destructuring allows unpack values from arrays, or properties from objects, into distinct variables.
let animal = {
name: "Elephant",
color: "Black",
age: 10
}
const {name, color, age} = animal;
console.log(name); // Elephant
console.log(color); // Black
console.log(age); // 10
let someArray = [100, 200, 300];
let [first, second, third] = someArray;
console.log(first); // 100
console.log(second); // 200
console.log(third); // 300
Spread syntax
Eg:
Combine array of string into single string
const items = ['This', 'is', 'a', 'sentence'];
console.log(...items); //This is a sentence
Combine multiple objects into single object
let front = {
engine: "1000cc",
steering: "Front"
};
let back = {
breaks: "Disk",
spoiler: "Sports"
};
let car = { ...front, ...back };
Rest Parameters
Rest parameter syntax allows to represent an indefinite number of arguments as an array. The rest of the parameters can be included in the function definition by using three dots … followed by the name of the array that will contain them.
function sum(...theArgs) {
console.log(theArgs[0]); // 1
}
sum(1, 2, 3);