Code Smell 116 - Variables Declared With 'var'

Code Smell 116 - Variables Declared With 'var'

Var, Let, Const: are all the same, aren't they?

Maxi Contieri
·Feb 23, 2022·

2 min read

Subscribe to my newsletter and never miss my upcoming articles

Play this article

Table of contents

  • Problems
  • Solutions
  • Context
  • Sample Code
  • Detection
  • Tags
  • Conclusion
  • Relations
  • More Info

TL;DR: Choose wisely your variable names, scope, and mutability.

Problems

Solutions

  1. Declare const all variables unless you need to change them

Context

Most languages don't need variable declarations.

Some other languages allow us to state mutability.

We should be strict and explicit with our declarations.

Sample Code

Wrong

var pi = 3.14
var universeAgeInYears = 13.800.000.000

pi = 3.1415 // no error
universeAgeInYears = 13.800.000.001 // no error

Right

const pi = 3.14 //Value cannot mutate or change 
let universeAgeInYears = 13.800.000.000 //Value can change

pi = 3.1415 // error. cannot define
universeAgeInYears = 13.800.000.001 // no error

Detection

[X] Manual

With mutation testing by forcing a 'const' declaration, we can check if a value remains constant and be more declarative by explicitly enforcing it.

Tags

  • Mutability

  • Javascript

Conclusion

Readability is always very important.

We need to explicitly state our intentions and usages.

Relations

More Info


Just as it is a good practice to make all fields private unless they need greater visibility, it is a good practice to make all fields final unless they need to be mutable.

Brian Goetz


This article is part of the CodeSmell Series.

 
Share this

Impressum

Technical Opinions are my own. I don't have the revealed truth.

Software Design is a creative activity. These are hints and not rigid rules.

I write on BackEnd Business Systems and OOP Design. My advice/experience might not suit other systems.

You can write me at info(at)maximilianocontieri.com