# Refactoring 008 - Convert Variables to Constant

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

# Problems Addressed

- [Mutability](https://maximilianocontieri.com/the-evil-powers-of-mutants)

- Code Optimization

# Related Code Smells

%[https://maximilianocontieri.com/code-smell-158-variables-not-variable]

%[https://maximilianocontieri.com/code-smell-127-mutable-constants]

%[https://maximilianocontieri.com/code-smell-116-variables-declared-with-var]

# Steps

1. Find the scope of the variable

2. Define a constant with the same scope

3. Replace the variable 

# Sample Code

## Before

[Gist Url]: # (https://gist.github.com/mcsee/3ae265e1ae7422164c175b16a7f822d3)

```javascript

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 

```

## After

[Gist Url]: # (https://gist.github.com/mcsee/e25d1ded85b4547d20fee70e4c1f0ca6)

```javascript

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);

```

# 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

%[https://maximilianocontieri.com/refactoring-003-extract-constant]

# See also

%[https://maximilianocontieri.com/the-evil-powers-of-mutants]

* * * 

This article is part of the Refactoring Series.
