Variable Declarations Best Practices in Js
Don’t declare variable twice
// bad: declaring variable twice
function test() {
"use strict";
var a = 1,
a = 2;
}
/*this will probably make your program not work as expected,
this can be fixed by renaming one of them
*/
function test() {
"use strict";
var a = 1,
b = 2;
}
Read more about it: already defined variable(jshint)
References
Use const for all of your references; avoid using var
Why? This ensures that you can’t reassign your references (mutation), which can lead to bugs and difficult to comprehend code.
// bad
var a = 1,
b = 2;
// good
const a = 1,
b = 2;
If you must mutate references, use let instead of var
Why? let is block-scoped rather than function-scoped like var.
// bad
var count = 1;
if (true) {
count += 1;
}
// good, use the let.
let count = 1;
if (true) {
count += 1;
}
Note that both let and const are block-scoped
// 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
Read more about references: js best practices
Use the literal syntax for array creation
// bad
const items = new Array();
// good
const items = [];
Read more about it: js array best practices
Use the literal syntax for object creation.
// bad
const item = new Object();
// good
const item = {};
Read more about it: js object best practices
Leave a comment