JS - Best Practices (let, const and var)

 

let and const are block scoped.

Therefore, referencing block-scoped identifiers before they are defined will produce a ReferenceError.

console.log(x); // ReferenceError: x is not defined
let x = 'hi';

// const and let only exist in the blocks they are defined in.
{
let a = 1;
const b = 1;
}
console.log(a); // ReferenceError
console.log(b); // ReferenceError

 

Use const for all references; avoid using var.
If you must reassign references, use let instead of var.
let is block-scoped rather than function-scoped like var.

Bad :

var count = 1;
if (true) {
count += 1;
}

Good :

// good, use the let.     
let count = 1;
if (true) {
     count += 1;
}

 
Read More :
http://exploringjs.com/es6/ch_core-features.html#sec_from-var-to-const
http://exploringjs.com/es6/ch_variables.html
 

js best practices

×