Why it’s bad practice to reassign function params

image from unsplash.com

Introduction

Reassigning the value of an argument variable mutates the arguments object. Mutation is the act of changing the source or the original element. Misuse of mutability can cause side effects to your software. In light of this fact, senior developers have across the globe found themselves opting for persistent data structures or Facebook’s immutable-js as a way to avoid mutation.

See this:

mutation in play

How do we avoid mutation?

Since mutation alters the original object and returns it, this gives us the idea of copying/cloning the original object.

An update shouldn’t change the original object, instead create a new object with the updated data.

Examples

  1. An object

2. An array

3. Function params!

Bonus

Methods to avoid that potentially mutates data

  1. Arrays
  • Array.prototype.push
  • Array.prototype.unshift
  • Array.prototype.splice
  • Array.prototype.pop
  • Array.prototype.shift

What to use instead

  • Array.prototype.slice & Array.prototype.concat
  • Array.prototype.slice & the ES6 Spread Operator
  • Array.prototype.filter

2. Objects

  • Direct addition
  • delete object.property

What to use instead

  • Object destructuring
  • Object.assign
  • Object Spread operator (still experimental)

Moving Forward

I believe this knowledge will change the way you write your JavaScript code.


Do you need to hire top developers? Talk to Andela to help you scale
Are you looking to accelerate your career as a developer? Andela is currently hiring senior developers.
Apply now.