javascriptfunctionpure-function

Can this function be called pure?


I think this is a pure function as it abide by the rules to be a pure function.

  1. It always return the same output.
  2. It has no side effects.

But in a medium blog, they said that this is a impure function.

function addNumbers(){
  let num1 = 100;
  let num2 = 1;
  return num1 + num2;
}

addNumbers();

Here is the link of the medium blog: https://medium.com/@simba3310/the-essential-guide-to-mastering-javascript-functions-2149f101fb1e

screenshot of the code blocks from the blog


Solution

  • The function you provided is an example of a pure nullary function, read this answer for more details.

    According to this article:

    • Pure functions return consistent results for identical inputs.
    • They do not modify external states or depend on mutable data.

    Since the function does not take any inputs, it will always return the exact same ouput, and it does not modify any external states, hence the function is pure.