I’ve been maintaining several
JavaScript driven websites. I found it is not easy to quickly make an update or enhancement in JavaScript when I only do it once in a while. So I decided to create this page to document all the tips and tricks that help me to keep my websites both personal and commercial to run at the optimal state.
I will cover JavaScript up to ECMAScript 6, also known as ECMAScript 2015. This is the latest version of the ECMAScript standard as of September 2019. ES6 is a significant update to the language, and the first update to the language since ES5 was standardized in 2009.
- use
===
instead of==
- Create an object constructor
- Create Anonymous Function or Self-calling Function
- Use Await To Make Several Asynchronous Calls
The ==
(or !=
) operator performs an automatic type conversion if needed. The ===
(or !==
) operator will not perform any conversion. It compares the value and the type, which could be considered faster than ==
.
[10] === 10 // is false [10] == 10 // is true '10' == 10 // is true '10' === 10 // is false [] == 0 // is true [] === 0 // is false '' == false // is true but true == "a" is false '' === false // is false
function Person(firstName, lastName){ this.firstName = firstName; this.lastName = lastName; } var Saad = new Person("Saad", "Mousliki");
This is usually called a Self-Invoked Anonymous Function or Immediately Invoked Function Expression (IIFE). It is a function that executes automatically when you create it, and has the following syntax:
(function(){ // some private code that will be executed automatically })(); (function(a,b){ var result = a+b; return result; })(10,20)
By using Promise.all and await keyword, it’s possible to await multiple async functions to finish :
await Promise.all([anAsyncCall(), thisIsAlsoAsync(), oneMore()])
JavaScript References:
https://www.techbeamers.com/javascript-tips-best-coding-practices/#javascript_tip4