Use
<!DOCTYPE html>
at the beginning of each HTML file
Include all
<link>
tags inside
<head>

                    <head>
                    <link rel="stylesheet" href="./styles/app.css" />
                    </head>
                
Include all
<script>
tags right before the
</body>
tag

                    <script src="./scripts/app.min.js"></script>
                    </body>
                
Include relevant
<meta>
tags (e.g.: for responsive layout, for character encoding, for Internet Explorer rendering engine usage):
                        
                            <meta charset="utf-8">
                            <meta http-equiv="x-ua-compatible" content="ie=edge">
                            <meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width">
                        
                    
Include favicon
<link>
tag and don't forget to add the
<title>
inside
<head>
:
<link rel="icon" href="favicon.ico">
Use semantic markup, not just throwing
<div>
s everywhere (try to use HTML5 elements and attributes where possible)
https://www.w3schools.com/html/html5_semantic_elements.asp
Know the difference between block-level elements
(
<div>, <p>, <h1>, <ul>, <section>
etc.) and inline elements
(
<span>, <a>
etc.)
Add suggestive
class
attributes to elements, in order to use them in CSS
Add
id
s where needed for binding handlers to elements in JS and make sure the
id
s are unique per page
Use
data-
attributes for storing relevant data on HTML elements
Be aware of which tags should be properly closed using end tags (e.g.:
</div>, </script>
) and which tags don't need to be closed (e.g.:
<input>
)
Use classes (e.g.:
.container
) wherever possible and avoid using IDs (e.g.:
#myButton
) for styling
Use 'normalize.css'
(
https://necolas.github.io/normalize.css/
) or 'reset.css'
(
https://meyerweb.com/eric/tools/css/reset/
) as the first CSS in your project, in order to remove/adjust default browser styling that may affect the look and feel
Use minimum specificity whenever possible
Use camelCase notation for IDs (e.g.:
#submitButton
) and dashed-notation for classes (e.g.:
.layer-wrapper
)
Don't repeat the same CSS selector in the same file:
                        
                            [100].wrapper .container button {
                            [101]    background-color: #f00;
                            [102]}
                            ..................................
                            [255].wrapper .container button {
                            [256]    text-transform: uppercase;
                            [257]}
                        
                    
Use shorthand notation where possible, instead of this:
                        
                            .container {
                                background-color: transparent;
                                background-image: url('../../images/pattern.png');
                                background-repeat: no-repeat;
                                background-position: 0 0;
                                background-size: 100% 100%;
                            }
                        
                    
use this:
                        
                            .container {
                                background: url('../../images/pattern.png') no-repeat 0 0 / 100% 100% transparent;
                            }
                        
                    
Place each selector on a separate line:
                        
                            body,
                            html {
                                width: 100%;
                                height: 100%;
                                overflow: hidden;
                            }
                        
                    
instead of:
                        
                            body, html {
                                width: 100%;
                                height: 100%;
                                overflow: hidden;
                            }
                        
                    
When using
z-index
assign it the smallest value that suits your needs:
Z-index only works on positioned elements:
position: absolute;
position: relative;
position: fixed;
Use Image Sprites for small images and icon fonts whenever possible
(e.g.
http://fontawesome.io/
,
http://glyphicons.com/
):

                    .icon,
                    .icon.facebook {
                        width: 54px;
                        height: 54px;
                        background: url('social-icons.jpg') no-repeat 0 0 transparent;
                    }

                    .icon.twitter {
                        background-position: -80px 0;
                    }
                
Wrap code inside IIFEs (Immediately Invokable Function Expressions) in order not to pollute the global namespace:
                    
                        (function(){
                            /*** Your code here...***/
                        })();//<- This paranthesis shows that the anonymous function is invoked right after it is read by the interpreter
                    
                
Use strict equality / inequality
===
/
!==
instead of simple equality / inequality
==
/
!=
:
                    
                        var a = 1,
                        b = '1';

                        if(a == b) { //<- true
                            //do something
                        }

                        if(a === b) { //<- false
                            //do something else
                        }
                    
                
Think about the Single Responsibility Principle (break code in multiple functions that only do one thing)
Comment the code (including JSDoc before function signature):

                    /**
                    * Adds 2 numbers
                    * @param param1 Number
                    * @param param2 Number
                    * @returns Number
                    */
                    function sum(param1, param2) {

                        if(typeof param1 !== 'number' && param2 !== 'number') {
                            throw new Error('Invalid parameters!');
                        }

                        return param1 + param2;
                    }
                
Use 'strict' mode inside functions:

                    (function(){
                    'use strict';

                        a = 1;
                    })();//Throws a reference error: 'a is not defined!'

                    (function(){
                        a = 1;
                    })();//Adds 'a' to the Global namespace => window.a = 1;
                
Use Closures in order to expose private members of functions / public APIs:

                    //utils.js
                    function MathUtils () {
                    var add = function(param1, param2) {

                        if (typeof param1 !== 'number' && typeof param2 !== 'number') {
                            throw new Error('Cannot perform operation, invalid parameters!');
                        }

                        return param1 + param2;
                    },

                    power = function(base, exponent) {

                        if (typeof base !== 'number' && typeof exponent !== 'number') {
                            throw new Error('Cannot perform operation, invalid parameters!');
                        }

                        return Math.pow(base, exponent);
                    };


                        return {
                            add: add,
                            pow: power
                        };
                    }

                    //app.js
                    (function(){
                    'use strict';

                        console.log(new MathUtils().pow(2, 3)); //logs 8
                    })();
                
Avoid styling from JS:
document.getElementById("submitButton").style.color = "red";
Learn about JS Scoping & Hoisting:

                    var foo = 1;

                    (function bar() {
                        if (!foo) {
                            var foo = 10;
                        }

                        alert(foo);
                    })();
                
Use camelCase notation for both
var
s and
function
names, and use verbs as function names (e.g.
readFromInput()
)
Cache jQuery objects:
Instead of:

                    $('section').on('click', function(e){
                        alert('Clicked on section!');
                    }

                    $('section').on('mouseover', function(e) {
                        alert('Mouse over section!');
                    }
                
you can do:

                    var section = $('section');

                    section.on('click', function(e){
                        alert('Clicked on section!');
                    }

                    section.on('mouseover', function(e) {
                    alert('Mouse over section!');
                    }
                
Use defensive coding (use
try{...}catch(){...}
,
check types using
typeof
, check object instances using
instanceof
etc.)
A few important features introduced in ES6:
  1. Default Parameters
  2. Template Literals
  3. Multi-line Strings
  4. Destructuring Assignment
  5. Enhanced Object Literals
  6. Arrow Functions
  7. Promises
  8. Block-scoped Constructs
    let
    and
    const
  9. Classes
  10. Modules
Default Parameters (ES5):
                    
                        var link = function (height, color, url) {
                            var height = height || 50
                            var color = color || 'red'
                            var url = url || 'http://example.com'
                            ...
                        }
                    
                
Default Parameters (ES6):
                    
                        var link = function(height = 50, color = 'red', url = 'http://example.com') {
                          ...
                        }
                    
                
Template Literals (ES5):
                    
                        var name = 'Your name is ' + first + ' ' + last + '.'
                        var url = 'http://localhost:3000/api/messages/' + id
                    
                
Template Literals (ES6):
                    
                        var name = `Your name is ${first} ${last}.`
                        var url = `http://localhost:3000/api/messages/${id}`
                    
                
Multi-line Strings (ES5):
                    
                        var roadPoem = 'Then took the other, as just as fair,\n\t'
                            + 'And having perhaps the better claim\n\t'
                            + 'Because it was grassy and wanted wear,\n\t'
                            + 'Though as for that the passing there\n\t'
                            + 'Had worn them really about the same,\n\t'

                        var fourAgreements = 'You have the right to be you.\n\
                            You can only be you when you do your best.'
                    
                
Multi-line Strings (ES6):
                    
                        var roadPoem = `Then took the other, as just as fair,
                            And having perhaps the better claim
                            Because it was grassy and wanted wear,
                            Though as for that the passing there
                            Had worn them really about the same,`

                        var fourAgreements = `You have the right to be you.
                            You can only be you when you do your best.`
                    
                
Destructuring Assignment (ES5):
                    
                        var data = $('body').data(), // data has properties house and mouse
                            house = data.house,
                            mouse = data.mouse

                        var jsonMiddleware = require('body-parser').json
                        var body = req.body, // body has username and password
                          username = body.username,
                          password = body.password
                    
                
Destructuring Assignment (ES6):
                    
                        var {house, mouse} = $('body').data() // we'll get house and mouse variables

                        var {json: jsonMiddleware} = require('body-parser')

                        var {username, password} = req.body

                        var [col1, col2]  = $('.column'),
                            [line1, line2, line3, , line5] = file.split('\n')
                    
                
Object Literals in ES5:
                    
                        var serviceBase = {port: 3000, url: 'example.com'},
                            getAccounts = function(){return [1,2,3]}

                        var accountServiceES5 = {
                          port: serviceBase.port,
                          url: serviceBase.url,
                          getAccounts: getAccounts,
                          toString: function() {
                            return JSON.stringify(this.valueOf())
                          },
                          getUrl: function() {return "http://" + this.url + ':' + this.port},
                          valueOf_1_2_3: getAccounts()
                        }
                    
                
Object Literals in ES6:
                    
                        var getAccounts = function(){return [1,2,3]}

                        var accountService = {
                            getAccounts,
                            toString() {return JSON.stringify((super.valueOf()))},
                            getUrl() {return "http://" + this.url + ':' + this.port},
                            [ 'valueOf_' + getAccounts().join('_') ]: getAccounts()
                        }
                    
                
Arrow Functions in ES6 allow easy handling of
this
: ES5 handling of
this
:
                    
                        var self = this
                        $('.btn').click(function(event){
                          self.sendData()
                        })
                    
                
With Arrow Functions:
                    
                        $('.btn').click((event) =>{
                          this.sendData()
                        })
                    
                
ES5 way of creating an Array based on another array:
                    
                        var ids = ['5632953c4e345e145fdf2df8','563295464e345e145fdf2df9']
                        var messages = ids.map(function (value) {
                          return "ID is " + value // explicit return
                        })
                    
                
With Arrow Functions and Template Literals:
                    
                        var ids = ['5632953c4e345e145fdf2df8','563295464e345e145fdf2df9']
                        var messages = ids.map(value => `ID is ${value}`) // implicit return
                    
                

ES6 introduces a standard Promise implementation

Example of ES5 delayed executions with
setTimeout()
:
                    
                        setTimeout(function(){
                          console.log('After 1 sec!');
                          setTimeout(function(){
                            console.log('After 2 sec!')
                          }, 1000)
                        }, 1000)
                    
                
Using ES6 Promises (and Arrow Functions):
                    
                        var wait1000 =  ()=> new Promise((resolve, reject)=> {setTimeout(resolve, 1000)})

                        wait1000()
                          .then(function() {
                            console.log('Yay!')
                            return wait1000()
                          })
                          .then(function() {
                            console.log('Wheeyee!')
                          })
                    
                
Block-Scoped Constructs
let
and
const
Example of variable scoping using
var
:
                    
                        function calculateTotalAmount (vip) {
                          var amount = 0
                          if (vip) {
                            var amount = 1
                          }
                          { // more blocks!
                            var amount = 100
                            {
                              var amount = 1000
                              }
                          }
                          return amount
                        }

                        console.log(calculateTotalAmount(true))
                    
                
Using
let
:
                    
                        function calculateTotalAmount (vip) {
                          var amount = 0 // probably should also be let, but you can mix var and let
                          if (vip) {
                            let amount = 1 // first amount is still 0
                          }
                          { // more blocks!
                            let amount = 100 // first amount is still 0
                            {
                              let amount = 1000 // first amount is still 0
                              }
                          }
                          return amount
                        }

                        console.log(calculateTotalAmount(true))
                    
                
Using
const
:
                    
                        function calculateTotalAmount (vip) {
                          const amount = 0
                          if (vip) {
                            const amount = 1
                          }
                          { // more blocks!
                            const amount = 100
                            {
                              const amount = 1000
                              }
                          }
                          return amount
                        }

                        console.log(calculateTotalAmount(true))
                    
                
Classes in ES6:
                    
                        class BaseModel {
                          constructor(options = {}, data = []) { // class constructor
                            this.name = 'Base'
                            this.url = 'http://example.com/api'
                            this.data = data
                            this.options = options
                          }

                            getName() { // class method
                              console.log(`Class name: ${this.name}`)
                            }
                        }
                    
                
Extending a base class:
                    
                        class AccountModel extends BaseModel {
                            constructor(options, data) {
                                super({private: true}, ['32113123123', '524214691']) //call the parent method with super
                                this.name = 'Account Model'
                                this.url +='/accounts/'
                            }
                             get accountsData() { //calculated attribute getter
                                // ... make XHR
                                return this.data
                              }
                        }
                    
                
Usage:
                    
                        let accounts = new AccountModel(5);
                        accounts.getName();
                        console.log('Data is: ', accounts.accountsData);
                    
                
Declaring a module and using it in ES5 (with require() in case of NodeJS):
                    
                        //module.js
                        module.exports = {
                          port: 3000,
                          getAccounts: function() {
                            ...
                          }
                        }

                        //main.js
                        var service = require('module.js')
                        console.log(service.port) // 3000
                    
                
ES6 modules:
                    
                        //module.js
                        export var port = 3000
                        export function getAccounts(url) {
                          ...
                        }

                        //main.js
                        import {port, getAccounts} from 'module'
                        console.log(port) // 3000
                        //or
                        import * as service from 'module'
                        console.log(service.port) // 3000
                    
                
Try it yourself using BABEL:
                    
                        https://babeljs.io/