Do not reinvent the wheel, JavaScript standards for LWC development

Published in Articles

1. Use let/const instead of var

The var statement declares a function-scoped variable while const and let statement declares a block-scoped local variable. But why you should not use var anymore? A lot of programming languages have block-scoped variables because code is more robust, it is easier to control variable lifetime, developers can declare variables inside blocks without worrying about overwriting previously declared variables.

Let's find different based on the example below:
// Created the function-scoped variable
{ var variable = 'junk'; } 
console.log(variable); // 'junk'
  
// Created the block-scoped local variable
{ let variable = 'junk'; } 
console.log(variable); // ReferenceError: variable is not defined

Now we know that var is a bad thing, but how to know when to use const and when let? Actually, const should be used by default for most cases. Const only prevents variable re-assigning, it does not make the entire object immutable
const myArray = [1, 2, 3];
myArray.push(4);
myArray = ['buster']; // TypeError: Assignment to constant variable.

Use let only if const is not an option. For example:
let i = 1;
i = i + 1;

2. Default parameters

You can put the default values right in the signature of the function

const sayHello = function(name = 'World!') {
    console.log('Hello ' + name);
}

sayHello(); // Hello World!
sayHello('there!'); // Hello there!

3. Template literals

Template literals is a useful feature that allows you to inject variables directly into a string. To create it use the backtick (`) instead of single quotes or double-quotes characters. Template literals can contain placeholders. These are indicated by the dollar sign and curly braces (${expression})

const name = 'World!';
const greeting = `Hello ${name}`;
console.log(greeting); // Hello World!

4. Arrow function expression

Arrow functions are a new syntax for writing JavaScript functions. It’s called "arrow functions" because it looks like this:

const func = (arg1, arg2, ...argN) => { 
    // function body
}

If the function body is a single expression, you can leave off the brackets and put it inline. The results of the expression will be returned by the function. Also, if there is only a single argument, you can even leave off the parenthesis around the argument
const greeting = (name) => `Hello ${name}`;
console.log(greeting('World!')); // Hello World!

Below examples illustrate the use of array .map() method. The function is called for each element present in the parent array, the returned value is added to result array
const numbers = [1, 2, 3, 4, 5];
const squares = numbers.map(x => x * x);
console.log(squares); // [1, 4, 9, 16, 25]

The .reduce() method reduces the array to a single value
const reducer = (accumulator, currentValue) => {
  return accumulator + currentValue;
};

const initialValue = 0;
const numbers = [1, 2, 3, 4, 5];

// 0 + 1 + 2 + 3 + 4 + 5 = 15
const total = numbers.reduce(reducer, initialValue);

The .filter() method would be helpful if you have an array and want only some of the element in it
const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const oddNumbers = numbers.filter(x => x % 2 === 1);
console.log(oddNumbers); // [1, 3, 5, 7, 9]

5. Spread operator

The operator's shape is three consecutive dots and is written as: ... . It is a useful and quick syntax for adding items to arrays, combining arrays or objects, and spreading an array out into a function's arguments

const array1 = [1, 2, 3];
const array2 = [4, 5, 6];
const result = [...array1, ...array2, 7, 8, 9];
console.log(result); // [1, 2, 3, 4, 5, 6, 7, 8, 9]
const obj1 = { foo: 'bar', x: 1 };
const obj2 = { foo: 'baz', y: 2 };
const clonedObj = { ...obj1 }; // Object { foo: "bar", x: 1 }
const mergedObj = { ...obj1, ...obj2 }; // Object { foo: "baz", x: 1, y: 2 }
const numbers = [1, 2, 3, 4, 5, 999];
const result = Math.max(...numbers);
console.log(result); // 999

6. Destructuring

Destructuring assignment is a special syntax that makes it possible to unpack arrays or objects into distinct variables

const rowData = ['Rick', 'Sanchez', This email address is being protected from spambots. You need JavaScript enabled to view it.'];
const [ firstName, lastName, email ] = rowData;
console.log(firstName, lastName); // Rick Sanchez
const contactDetails = {
    firstName: 'Rick',
    lastName: 'Sanchez',
    email: This email address is being protected from spambots. You need JavaScript enabled to view it.'
};
const { firstName, email } = contactDetails;
console.log(firstName, email); // Rick This email address is being protected from spambots. You need JavaScript enabled to view it.

7. Promises

Promises can simplify code that handles the success or failure of asynchronous calls, or code that chains together multiple asynchronous calls. In this example, we use setTimeout(...) to simulate async code

let myPromise = new Promise((resolve, reject) => {
  setTimeout(
    () => resolve("Success!"), 
    1000
  )
}) 

myPromise.then((successMessage) => {
  console.log(successMessage) // Success!
});

8. Async/Await

There is a special syntax to work with promises in a more comfortable fashion, called "async/await". Many developers think this syntax is easier to read and understand. It resembles the top-down approach that you see in traditional synchronous code. But really, it's just a different way of working with promises

function resolveAfterOneSecond(value) {
  return new Promise((resolve, reject) => {
    setTimeout(
      () => resolve(`Successfully completed: ${value}`), 
      1000
    )
  })
}

async function asyncCall() {
  const result = await resolveAfterOneSecond("1st Call");
  console.log(result); // Successfully completed: 1st Call
}
      
asyncCall();


Useful links:

Comments powered by CComment