Computer >> Computer tutorials >  >> Programming >> Javascript

What is a pure function in JavaScript?


Pure function

A pure function is a deterministic function. This means when a same input is passed every time, the function will return same output. In mathematical terms it is nothing but a well defined function.

A pure function will have the following properties

  • It depends only on its own arguments.

  • It wont try to change variables out of its scope.

  • It doesn't produce any side effects.

The following example is not a pure function because rather than depending on its own variables, the function is depending on variables(val1 and val2) that are out of its scope.

Example

<html>
<body>
<script>
   let val1 = 6;
   let val2 = 4;
   function pure() {
      return val1 * val2;
   }
   document.write(pure());
</script>
</body>
</html>

output

24


In the following example the function, even though depending on its own arguments, is also depending on some outside variables(val). So it is not a pure function

Example

<html>
<body>
<script>
   function pure(arg) {
      let val = 100;
      return val* arg;
   }
   document.write(pure(2));
</script>
</body>
</html>

output

200


The following example displays a pure function because there are no outside variables involved while the function is performing its tasks. The function returns the same output when a same parameter is passed to it 

Example

<html>
<body>
   <script>
      function pure(arg) {
         return 4 * arg;
      }
      document.write(pure(2));
   </script>
</body>
</html>

output

8