skip to Main Content

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();

3

Answers


  1. Yes, it’s a pure function because it follows two key rules :

    • No side effects

    • Same input, same output

    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
  3. Your function is not pure because it depends on hardcoded values instead of external inputs.
    In your case your are breaking the following pure function rule.

    • No reliance on internal or external state or variables.

    Updating to following will make your function pure

    function get101(){
     return 101;
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search