Check out my books on Amazon at https://www.amazon.com/John-Au-Yeung/e/B08FT5NT62
Subscribe to my email list now at http://jauyeung.net/subscribe/
Like any other programming language, JavaScript has its own list of best practices to make programs easier to read and maintain. There are lots of tricky parts to JavaScript, so there are many things to avoid.
We can follow some best practices to make our JavaScript code easy to read.
In this article, we look at how to declare variables in an easy-to-read way. Also, we look at ways to avoid declaring global variables and hiding private variables from the outside.
Avoid Global Variables
We should avoid the use of global variables as much as possible for various reasons.
One is that they’re easy to overwrite in different places since they’re available everywhere. They can also overwrite things in the window
object since global variables are properties of the window
object.
These two are real issues that make our code hard to follow. Therefore, we should define local variables as much as possible. We can define local variables by using the var
, let
, or const
keywords.
Variables defined with var
are available at the level where they are defined and below before they are defined. For example, if we write:
Then we get undefined
for the first console.log
and one for the second log.
It’s the same as writing:
Variables declared with let
are available only after they’re defined, so if we gave:
We get the error:
Uncaught ReferenceError: Cannot access ‘x’ before initialization
With the const
keyword, we define constants that can only be assigned once and never again. It’s also available only after it’s declared, unlike var
.
For example, we can write:
const log = () => {
console.log(x);
}
const x = 1;
log();
Calling log
before const x = 1
will also get us:
Uncaught ReferenceError: Cannot access ‘x’ before initialization
If we want variables that are available in different parts of a program, we should use JavaScript modules and then build the modules into one or several large files when we release our code. This is available since ES6.
We can export
our variables and import
it in other modules. There’s also export default
to export the whole module. This way, we only export things that should be available outside the module and keep everything else private.
We can also use closures to keep variables inside a function so they can’t be accessed outside. An example of a simple closure would be:
const multiply = () => {
const x = 3;
return () => x \* 2;
}
We keep x
inside the multiply
function so that it can’t be accessed outside and return a function that does something with it.
Then, we call it by writing:
console.log(multiply()());
Always Declare Local Variables
As a corollary, we should always declare local variables. We should always declare local variables and constants with var
, let
, or const
.
Otherwise, it’ll be declared as a global variable as a property of window
which we definitely don’t want.
For example, we should never write:
x = 1;
Instead, we should write:
let x = 1;
Fortunately, JavaScript strict mode doesn’t allow undeclared variables, so we can’t accidentally create global variables.
Also, JavaScript modules have strict mode enabled by default so we also can’t define global variables accidentally in there.
Photo by Francesco De Tommaso on Unsplash
Putting Variables and Constant Declarations on Top
Putting variable and constant declarations on top makes our code cleaner as everything is on top. It also stops us from accidentally referencing things declared with let
or const
before they are defined.
If strict mode is off, we also avoid defining global variables. And we also avoid accidental re-declarations of variables. Re-declarations should be caught by many text editors, but it’s still a possibility.
We can make multiple variable declarations in one line by separating variable names with commas. For example, we can write:
let x, y;
x = 1;
y = 1;
console.log(x, y);
Then we get:
1 1
From the console.log
.
We can do the same for loops:
let i;
for (i = 0; i < 10; i++) {
console.log(i);
}
Initialize Variables When Declaring Them
It’s a good idea to initialize our variables or constants with values when declaring them. It prevents undefined value errors, and we can both declare the variable or constant and set an initial value to it all in one line.
Otherwise, we have one line for declaring the variable or constant and another line for setting its value.
For example, we can write:
let x = 1,
y = 1;
To declare both x
and y
.
This is much shorter than writing:
let x;
let y;
x = 1;
y = 1;
We can declare and initialize multiple variables by separating each declaration and assignment with a comma.
Conclusion
Here are some basic best practices for declaring and initializing variables.
We looked at how to declare variables cleanly and how to avoid declaring global variables. There is a lot more to writing clean JavaScript programs so stay tuned for more.