You can prevent undefined
TL;DR: Declare your variables and look after the scope
-
Readability
-
Least Surprise Principle violation
-
Variable Shadowing
-
Be explicit on declarations
-
Use 'const' declaration when possible.
-
Declare variables at the beginning of the scope.
-
Use strict mode
Hoisting allows variable declarations to be moved to the top of their containing scope during the compilation phase.
Variables declared with var and function declarations are "hoisted" to the top of their respective scopes automatically in several languages.
console.log(willBeDefinedLater);
// Output: undefined (but no error)
var willBeDefinedLater = "Beatriz";
console.log(willBeDefinedLater);
// Output: "Beatriz"
const dante = "abandon hope all ye who enter here";
// Declaring a constant 'dante'
// with value "abandon hope all ye who enter here"
console.log(dante);
// Output: "abandon hope all ye who enter here"
dante = "Divine Comedy"; // Error: Assignment to constant variable
[X] Semi-Automatic
We can perform mutation testing to check if changing the scope of the variables brings unexpected results.
- Mutability
Hoisting is yet another magic tool some compilers provide to favor lazy programmers.
But if it fights back in debugging time.
Code Smell 116 - Variables Declared With 'var'
Code Smell 42 - Warnings/Strict Mode Off
Code Smells are my opinion.
Photo by Ash from Modern Afflatus on Unsplash
The best error message is the one that never shows up.
Thomas Fuchs
Software Engineering Great Quotes
This article is part of the CodeSmell Series.