Improve your code by using Pure functions is JavaScript

Improve your code by using Pure functions is JavaScript

If you want to improve your code, you must consider using Pure functions

·

2 min read

Intro

💡JavaScript tip: Use pure functions wherever possible!

Untitled.png

What is a pure function exactly?

The simplest definition for a pure function is it gives the same output for the same inputs.

If you take a look at the example code above, you can notice that the pure function is not performing any side effects.

The function just runs based on its arguments, not by external or global variables etc. This is the concept of pure function.

Effectively, a pure function’s return value is based only on its inputs and has no other dependencies or effects on the overall program.

Consider this function, it looks pure because it is not performing any side effects. But this function does not return the same value when we run the function! So it is not pure.

Untitled2.png

Why pure functions?

Readability:

Pure functions are much easier to read and understand what exactly they are doing.

All the dependencies and inputs are specified in the parameters so we exactly know what the function is doing since it’s not mutating anything in global scope.

Testing:

Since a function doesn’t do have any side effects, it is easier to test by passing same inputs and expecting a certain output.

Outro

That's all, folks!

If you really liked it and want to get more content like this, you can follow me on Hashnode and on Twitter @syedbasim and I will keep posting stuff like this on:

  • 🎨 HTML & CSS
  • ⚛ React & Nextjs
  • 🟦 TypeScript
  • 🏃‍♂️ My journey & Achievements