DEV Community

Maxi Contieri
Maxi Contieri

Posted on • Edited on • Originally published at maximilianocontieri.com

2

Code Smell 86 - Mutable Const Arrays

Const declares something to be constant. Can it mutate?

TL;DR: Don't rely on languages cheating about directives.

Problems

  • Unexpected side effects.

  • Accidental complexity.

Solutions

  1. Use better languages

  2. Use spread operator

Sample Code

Wrong

const array = [1, 2];

array.push(3)

//array => [1, 2, 3]
//Wasn't it constant ?
//constant != immutable ?
Enter fullscreen mode Exit fullscreen mode

Right

const array = [1, 2];

const newArray = [...array,3 ]

//array => [1, 2] Didn't mutate
//newArray = [1, 2, 3]
Enter fullscreen mode Exit fullscreen mode

Detection

Since this is a "language feature", we can explicitly forbid it.

Tags

  • Mutability

  • JavaScript

Conclusion

We should always favour immutability on our designs and take extra care with side effects.

More Info

Credits

Photo by Zorik D on Unsplash

Thank you, @oliverjumpertz for this tip.


Correctness is clearly the prime quality. If a system does not do what it is supposed to do, then everything else about it matters little.

Bertrand Meyer


This article is part of the CodeSmell Series.

Hot sauce if you're wrong - web dev trivia for staff engineers

Hot sauce if you're wrong · web dev trivia for staff engineers (Chris vs Jeremy, Leet Heat S1.E4)

  • Shipping Fast: Test your knowledge of deployment strategies and techniques
  • Authentication: Prove you know your OAuth from your JWT
  • CSS: Demonstrate your styling expertise under pressure
  • Acronyms: Decode the alphabet soup of web development
  • Accessibility: Show your commitment to building for everyone

Contestants must answer rapid-fire questions across the full stack of modern web development. Get it right, earn points. Get it wrong? The spice level goes up!

Watch Video 🌶️🔥

Top comments (0)

👋 Kindness is contagious

If this **helped, please leave a ❤️ or a friendly comment!

Okay