DEV Community

Mursal Furqan Kumbhar
Mursal Furqan Kumbhar

Posted on

Good JavaScript Developers do thisπŸ‘‡

Today, we shall discuss some techniques that are used by pretty good JavaScript developers.

  • Minimize the use of global variables. Global variables and functions can be overwritten by other scripts.

  • All variables used in functions should be declared as local variables.

  • Local variables must be declared with the var, let or const keywords, otherwise they will become global variables.

  • It's a good coding practice to put all declaration at top of each script/function. This gives the code a cleaner look and make it easier to avoid unwanted global variables.

// Declaring at the beginning
let alpha, beta, omega

// Use them at later stage
alpha = " the leaders"
beta = "followers"
omega = "viewers"
Enter fullscreen mode Exit fullscreen mode
  • It's a good coding practice to initialize variables when you declare them. This gives the code a cleaner look and provides a single place to initialize variables.
// Declaring and initiate at the beginning
let alpha = "The leaders"
let beta = "Followers"
const omega = "Viewers"
Enter fullscreen mode Exit fullscreen mode
  • Declaring objects and Arrays with const prevents any accidental change of type or value Without const
let teacher = {name:"Mursal", subject:"IT"}
teacher = "He who teaches"
Enter fullscreen mode Exit fullscreen mode

With const

const teacher = {name:"Mursal", subject:"IT"}
//Throws an error at this line since not possible
teacher = "He who teaches"
Enter fullscreen mode Exit fullscreen mode
  • JavaScript is a loosely typed language which means you don't specify the type of variable while declaring like int, float, or char. You just give it data of any type and that could be overwritten.
let x = "Hello" // type = string
let x = 5 // change: type = int
Enter fullscreen mode Exit fullscreen mode

A good solution is to declare all the variable which you don't want to reassign later with the const keyword.

  • If a function is called with a missing argument, the vale of the argument is set to undefined, and that could break your code. Avoid it using default parameters, for example:
function (a=1, b=2){
     /*function code/
}
Enter fullscreen mode Exit fullscreen mode

Now if an argument will be missing, then the default value will be used, and your code won't break.

Top comments (0)