DEV Community

Cover image for Code Smell 213 - Hoisting
Maxi Contieri
Maxi Contieri

Posted on • Originally published at maximilianocontieri.com

3 1

Code Smell 213 - Hoisting

You can prevent undefined

TL;DR: Declare your variables and watch the scope

Problems

  • Readability

  • Least Surprise Principle violation

  • Variable Shadowing

Solutions

  1. Be explicit on declarations

  2. Use 'const' declaration when possible.

  3. Declare variables at the beginning of the scope.

  4. Use strict mode

Context

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.

Sample Code

Wrong

console.log(willBeDefinedLater); 
// Output: undefined (but no error)

var willBeDefinedLater = "Beatriz";
console.log(willBeDefinedLater); 
// Output: "Beatriz"
Enter fullscreen mode Exit fullscreen mode

Right

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
Enter fullscreen mode Exit fullscreen mode

Detection

[X] Semi-Automatic

We can perform mutation testing to check if changing the scope of the variables brings unexpected results.

Tags

  • Mutability

Conclusion

Hoisting is yet another magic tool some compilers provide to favor lazy programmers.

But if it fights back in debugging time.

Relations

More Info

Wikipedia

Disclaimer

Code Smells are my opinion.

Credits

Photo by Ash from Modern Afflatus on Unsplash


The best error message is the one that never shows up.

Thomas Fuchs


This article is part of the CodeSmell Series.

Warp.dev image

The best coding agent. Backed by benchmarks.

Warp outperforms every other coding agent on the market, and gives you full control over which model you use. Get started now for free, or upgrade and unlock 2.5x AI credits on Warp's paid plans.

Download Warp

Top comments (0)

Dev Diairies image

User Feedback & The Pivot That Saved The Project

🔥 Check out Episode 3 of Dev Diairies, following a successful Hackathon project turned startup.

Watch full video 🎥

👋 Kindness is contagious

Delve into a trove of insights in this thoughtful post, celebrated by the welcoming DEV Community. Programmers of every stripe are invited to share their viewpoints and enrich our collective expertise.

A simple “thank you” can brighten someone’s day—drop yours in the comments below!

On DEV, exchanging knowledge lightens our path and forges deeper connections. Found this valuable? A quick note of gratitude to the author can make all the difference.

Get Started