Home > front end >  Can the below function be called as pure function(JS)?
Can the below function be called as pure function(JS)?

Time:03-24

I was recently going through javascript pure functions. I found out that the pure function should not have any global dependencies, so according to this i encountered a doubt which i have try to explain below.

function parent(){

 const count =1;
 const data = 30;

 function child (){
    let sum = count   data;
    return sum;
 }

 function child2(count, data){

    let final = count   data;
    return final;
 }
}

So according to the above snippet, can the child and child2 function be called as pure function? If child function is called as pure function they why because it is taking the parameters from the parent function defined above.

The output of both the functions will be same but which one would be called as pure function. This might be a very simple question but any help will be useful.

CodePudding user response:

A pure function is a function that do not have any dependency and will return a same result with same arguments everywhere. you can move child2 function to another file and that will work as well but you can not more child function anywhere because it needs the variables outside of it's scope. so the answer is: the child function is not pure and the child2 function is pure.

CodePudding user response:

It's only about scope and variables

function parent(){
  //
  // Parent function scope
  let count = 1;
  let data = 30;

  function child(){
    //
    // Child scope
    let sum = count   data;
    //
    // Change variable 'count' in PARENT scope
    count = 10;
    //
    // Return
    return sum;
  }

  //
  // Result will be 31
  const res1 = child();
  console.log(`Result 1: ${res1}`);

  function child2(count, data){
    //
    // Child2 scope
    let final = count   data;
    //
    // Change variable 'count' in child2 (CURRENT) scope
    count = 20;
    //
    // Return
    return final;
  }

  //
  // Result will be 40
  const res2 = child2(count, data);
  console.log(`Result 2: ${res2}`);

  //
  // Result will be 40
  const res3 = child();
  console.log(`Result 3: ${res3}`);
}

// Run parent
parent();

  • Related