Showing posts with label How to write JavaScript code. Show all posts
Showing posts with label How to write JavaScript code. Show all posts

Friday, July 14, 2017

JavaScript Best Practices Checklist / Important Things

Learning new things every day is a great habit that makes people great and ideal human being. As a developer, it is a part of our job. Developers are always accustomed to learn new things regularly. Sometimes, it becomes part of our daily work and sometimes it happens for more curious minds who advance always themselves with new technology and best practices.

Best practices is a significant coding style for every professional software developer. Your code is not enough good when machine can only read it and other developers can not. Your code should be human readable too. That's why ideal developers follow best practices for their coding style. It makes their code more sophisticated, readable, elegant, and comprehensive for every other developer.

In this article, I will point out a few important JavaScript best practices that you can remember easily.

1. Avoid polluting global scope. Always use IIFE (Immediately-Invoked Function Expression)
(function () {
   var foo = 12;
   console.log(foo);
   // 12
})();
 
 More Examples:
 
const getName = function () { }()     // ✗ avoid 
 
const getName = (function () { }())   // ✓ ok 
const getName = (function () { })()   // ✓ ok 

2. Use "use strict" to protect version compatibility and unexpected error. Best to use inside IIFE
(function () {
   "use strict";
   var foo = 40;
   console.log(foo);
   // 40
})();