The Benefits of Using a Constant

Angular: The Full Gamut Edition

Charlie Greenman
September 17, 2020
2 min read

What is a Constant

A constant is assigning a variable to a particular value. Whenever we would like to use that value, instead of typing out the value, we would use the variable name.

At first glance, however, it might seem counter-intuitive. Why use the constant value, if it is literally the same name as the actual value it is referring to?

Example of a Constant

//Update last updated value to have latest payload data

new updateValue(payload, LAST_UPDATED);

Benefits of a Constant

Creates a Table of Contents

When one creates a series of constants in a particular file for a certain component, one can peruse through the constant file, being able to see all actionable items in one. For instance, the following:

// ValueActionTypes.js
import * as types from "../ValueActionTypes";
export class UpdateValue implements Action {
  readonly type = UPDATE_VALUE;
  constructor(public payload);
export class AddValue implements Action {
  readonly type = ADD_VALUE;
  constructor(public payload);
export class DeleteValue implements Action {
  readonly type = DELETE_VALUE;
  constructor(public payload);
/* instead of parsing through our ValueActionTypes file, and other files potentially using constants, we can simply look at our ValueActionTypes.js file to get an idea of what we plan on implementing in our component.

Communicate to Maintainers

If using a constant value, it signifies to future maintainers of your code, that this a value that should immutable. This further documents the intent of the code.

Help Secure Values

When typing in a string for a particular constant value, we must apply particular diligence to make sure it is typed appropriately. Typing a value in one place, allows the developer to place extra diligence when typing a particular value. Allowing a developer to simply copy and paste the value from a singular expected location(the constant value) to 5 different places.

More articles similar to this


Razroo is committed towards contributing to open source. Take the pledge towards open source by tweeting, #itaketherazroopledge to @_Razroo on twitter. One of our associates will get back to you and set you up with an open source project to work on.