DEV Community

Cover image for Refactoring 008 - Convert Variables to Constant
Maxi Contieri
Maxi Contieri

Posted on • Originally published at maximilianocontieri.com

3

Refactoring 008 - Convert Variables to Constant

If I see a Variable that does not change. I call that variable a constant

TL;DR: Be explicit on what mutates and what does not.

Problems Addressed

Related Code Smells

Steps

  1. Find the scope of the variable

  2. Define a constant with the same scope

  3. Replace the variable

Sample Code

Before


let lightSpeed = 300000;

var gravity = 9.8;



// 1. Find the scope of the variable

// 2. Define a constant with the same scope

// 3. Replace the variable 

Enter fullscreen mode Exit fullscreen mode

After


const lightSpeed = 300000;

const gravity = 9.8;



// 1. Find the scope of the variable

// 2. Define a constant with the same scope

// 3. Replace the variable 



// If the object is compound, 

// we might need Object.freeze(gravity);

Enter fullscreen mode Exit fullscreen mode

Type

[X] Automatic

Our IDEs can check if a variable is written but never updated.

Safety

This is a safe refactor.

Why code is better?

Code is more compact and declarative.

We can make and step further and use operators like var, let, const, etc.

The scope is more clear.

Tags

  • Mutability

Related Refactorings

See also


This article is part of the Refactoring Series.

SurveyJS custom survey software

Build Your Own Forms without Manual Coding

SurveyJS UI libraries let you build a JSON-based form management system that integrates with any backend, giving you full control over your data with no user limits. Includes support for custom question types, skip logic, an integrated CSS editor, PDF export, real-time analytics, and more.

Learn more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Immerse yourself in a wealth of knowledge with this piece, supported by the inclusive DEV Community—every developer, no matter where they are in their journey, is invited to contribute to our collective wisdom.

A simple “thank you” goes a long way—express your gratitude below in the comments!

Gathering insights enriches our journey on DEV and fortifies our community ties. Did you find this article valuable? Taking a moment to thank the author can have a significant impact.

Okay