DEV Community

Cover image for 7 Practices to Create Good JavaScript Variables
Alex Devero
Alex Devero

Posted on • Originally published at blog.alexdevero.com

7 Practices to Create Good JavaScript Variables

As a developer you work with variables every day. One interesting thing about variables is that they can have a big impact. They can make your work much easier or much harder. This post will show you seven practices that will help you create good JavaScript variables and make your work easier.

Use meaningful and self-explanatory variable names

This is one of those practices that are very easy and quick to implement, but also often neglected. This is unfortunate because this simple practice can have a big impact. It can help make code much cleaner and easier to scan. It can save developers a lot of time. Think about it.

When you use meaningful and self-explanatory names for variable you need less time to remember what that thing does. When you get back to that piece of code later, you don't have to think about is that thing supposed to do, or what it is supposed to be used for. You read the name and everything immediately makes sense.

Yes, it is easier to use some abbreviation or placeholder name that just came to mind. However, that time you saved when you named that variable will be spent later when you will try to figure out what that thing does. It can take even more time to make sense of that cryptic name than to come up with meaningful and self-explanatory name.

// Before:
const flb = fs.readFileSync('/foo/bar/bills.txt', 'utf8')
const cdt = new Date()
const cy = cd.getYear()
const cm = cd.getMonth()
const cd = cd.getDay()
const anms = ['dog', 'cat', 'bear', 'wolf', 'lion']
const clgs = ['Jack', 'Drake', 'Jill']


// After:
const fileWithBills = fs.readFileSync('/foo/bar/bills.txt', 'utf8')
const currentDate = new Date()
const currentYear = cd.getYear()
const currentMonth = cd.getMonth()
const currentDay = cd.getDay()
const animals = ['dog', 'cat', 'bear', 'wolf', 'lion']
const colleagues = ['Jack', 'Drake', 'Jill']
Enter fullscreen mode Exit fullscreen mode

This practice has another benefit. Your code will become easier to search through. It is easier to search for "fileWithBills" or "bills" when you want to find variable with a file with bills than for "fl", "flb", "bls" or whatever came to mind as first back then. Consider this time saved/wasted next time you want to name a variable.

Keep variables local

When you declare variables, it is usually better to keep them local. This will help you avoid accidental collisions. Most importantly, it will help you avoid polluting global namespace with variables that may become redundant at some moment. So, try to avoid declaring variables as global by default.

Instead, declare your variables at the same scope you want to use them. If you want to use some variable in a specific function, declare it inside that function, not as global. This will not be applicable to situations where you want to use some variable in multiple places.

When this happens, it is fine to define that variable as global so you can reference it from any scope.

// Before (global variable):
const users = ['joejoe', 'steph', 'phill']

function someFunctionUsingUsers() {
  // Do something with data in "users" variable...
}


// After (local variable):
function someFunctionUsingUsers() {
  // Make "users" variable local:
  const users = ['joejoe', 'steph', 'phill']

  // Do something with data in "users" variable...
}


// Variable is used across codebase:
// Keep "users" variable global:
const users = ['joejoe', 'steph', 'phill']

function someFunctionUsingUsers() {
  // Do something with data in "users" variable...
}

function anotherFunctionUsingUsers() {
  // Do something with data in "users" variable...
}

function yetAnotherFunctionUsingUsers() {
  // Do something with data in "users" variable...
}
Enter fullscreen mode Exit fullscreen mode

Prefer let and const over var

When declaring JavaScript variables, prefer using let and const variables. These two variables are not initialized during hoisting. The var is hoisted and it can sometimes lead to problems.

// var:
console.log(pet)
// Output:
// undefined

var pet
pet = 'turtle'

// let and const:
console.log(pet)
// Output:
// ReferenceError: Cannot access 'pet' before initialization

let pet
pet = 'armadillo'
Enter fullscreen mode Exit fullscreen mode

Unlike var, let and const are also block-scoped variables. When you declare them in some code block, they will be visible and accessible only there. This means that let and const variables declared inside a code block will not collide with variables, with the same name, declared outside that code block.

By code blocks, we are also talking about code blocks created with if...else statements and loops. This doesn't apply to var variables. The var variable is not block-scope. It works only in two scopes, global and local (function scope). Declaring var variable inside a block code that is not a function body, or inside it, will lead to global variable.

This variable will be, by default, visible and accessible from everywhere and can collide with other variables.

// Before with var:
// Create global var variable:
var name = 'Jack'

if (true) {
  // Create var variable in if...else block
  // with the same name as the global variable:
  var name = 'Tobias'
}

// Log the value of global "name" variable:
console.log(name)
// Output:
// 'Tobias'


// After with let (and also const):
// Create global let variable:
let name = 'Victoria'

if (true) {
  // Create let variable in if...else block
  // with the same name as the global variable:
  let name = 'Susan'
}

// Log the value of global "name" variable:
console.log(name)
// Output:
// 'Victoria'
Enter fullscreen mode Exit fullscreen mode

Use one let and const per assignment

This practice may seem to have smaller impact, but it can still make your work at least a bit easier. There are two reasons for using one let and const per assignment. The first reason is that one let and const per assignment allows you to step through each declaration with debugger (in dev tools).

This can make it easier to work with code and debug potential issues. The second reason is to avoid accidental swap of comma (,) with semicolon (;) and the other way around. This can happen when you write the code and also when you read it. Well, especially when you read it. It is easy to confuse , with ;.

// Before (let/const and multiple assignments):
const name = 'Tommy'
age = 32
career = 'DevOps engineer'
skills = ['git', 'docker', 'kubernetes', 'JavaScript', 'serverless']

// After (let/const and one assignment):
const name = 'Tommy'
const age = 32
const career = 'DevOps engineer'
const skills = ['git', 'docker', 'kubernetes', 'JavaScript', 'serverless']
Enter fullscreen mode Exit fullscreen mode

Initialize variables when declaring them

There are two reasons why it is better to initialize JavaScript variables when you declare them. The first reason is that it helps you avoid potential errors when some variable is undefined. This can happen sometimes. It is very easy to declare a variable and reference it before you initialize it.

The second reason is purely pragmatic and aesthetic. Initializing variables when you declare them helps you make your code shorter. Doing these two tasks separately, you would need two lines, or more. Doing them at the same time requires just one line on code, or at least fewer lines than the alternative.

// Before:
// Declare variables:
let name, age, hobbies

// ... and initialize them later:
name = 'Joe'
age = 57
hobbies = ['playing games', 'reading books']


// After:
// Declare and initialize variables:
let name = 'Joe'
let age = 57
let hobbies = ['playing games', 'reading books']
Enter fullscreen mode Exit fullscreen mode

Declare variables on the top

Whenever possible, try to declare your JavaScript variables on the top of current scope. This serves three purposes. First, it helps make your code cleaner. When you, and other people who work with your code, know all variables are declared at the top of the scope they know where to look when they need to.

Without this practice you would have to search through the code when looking for a specific variable. The second reason is that it helps you avoid referencing variables before they are defined. When all variables are declared on the top, anything that follows can safely reference these variables (if you work with let or const).

The third reason is that it makes it easier to avoid accidentally re-declaring existing variables. This is less likely to happen with modern IDEs and intellisense. However, it is still possible. This possibility is lower when all JavaScript variables are on the top and you can quickly check if some name is already used.

Create variables where you use them

This may seem like an exception to the previous rule. It might be. However, special cases sometimes require special approach. One of these cases is when you assign variables that you want to use on one specific place, for one thing. In this situation, it is better to create that variable at that place or near it.

Doing this will help you group related code together. This grouping will make your code cleaner and easier to scan and understand.

// Before:
const stuff = ['mess']

// a lot of code...
// a lot of code...
// a lot of code...
// a lot of code...
// a lot of code...
// a lot of code...
// a lot of code...
// a lot of code...
// a lot of code...

function functionUsingStuff() {
  // Do something with data in "stuff" variable...
}


// After:
// a lot of code...
// a lot of code...
// a lot of code...
// a lot of code...
// a lot of code...
// a lot of code...
// a lot of code...
// a lot of code...
// a lot of code...

const stuff = ['mess']
function functionUsingStuff() {
  // Do something with data in "stuff" variable...
}


// Alternately:
// a lot of code...
// a lot of code...
// a lot of code...
// a lot of code...
// a lot of code...
// a lot of code...
// a lot of code...
// a lot of code...
// a lot of code...

function functionUsingStuff() {
  const stuff = ['mess'] // i.e. keep variables local
  // Do something with data in "stuff" variable...
}
Enter fullscreen mode Exit fullscreen mode

Conclusion: 7 Practices to create good JavaScript variables

Naming JavaScript variables doesn't have to a rocket science. There are some practices that are easy to implement that will make your work easier. I hope that these seven we discussed will help you create good JavaScript variables and make your code cleaner.

Discussion (1)

Collapse
renatoayau profile image
Renato Ayau

Good post, thanks