code-quality

Variable Declarations Best Practices in Js

best practices in js compiled from various sources like airbnb and jshint

js best practices
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: <a href=https://github.com/airbnb/javascript#references rel=“nofollow” target=“_blank”>js best practices

Use the literal syntax for array creation

// bad
const items = new Array();
 
// good
const items = [];
 

Read more about it: <a href=https://github.com/airbnb/javascript#arrays rel=“nofollow” target=“_blank”>js array best practices

Use the literal syntax for object creation.

// bad
const item = new Object();
 
// good
const item = {};

Read more about it: <a href=https://github.com/airbnb/javascript#objects rel=“nofollow” target=“_blank”>js object best practices

About the author

Prakash Poudel Sharma

Engineering Manager · Product Owner · Varicon

Engineering Manager at Varicon, leading the Onboarding squad as Product Owner. Eleven years of building software — first as a programmer, then as a founder, now sharpening the product craft from the inside of a focused team.

Keep reading

More on this

Comments