mrhm-dev / full-stack-army

569 stars 332 forks source link

Pre or Impure Function #75

Open nuruddin-bin-hoda opened 1 year ago

nuruddin-bin-hoda commented 1 year ago
function sum(num1, num2) {
  num2 = 5;

  return num1 + num2;
}

console.log(sum(1, 2)); // => 6

Argument কে যদি muted করা হয় তাহলে কি সেটা Pure Function থাকবে না Non Pure Function হয়ে যাবে??

aliakkas006 commented 1 year ago

If we muted the argument, then it becomes impure function. It modifies the value of the num2 parameter within the function body.

minhajul-im commented 1 year ago

a pure function is a function (a block of code) that always returns the same result if the same arguments are passed. it doesn't depend on any state or data change during a program’s execution. rather, it only depends on its input arguments.

the function modifies the value of num2 to 5 within the function body. even though num2 is a parameter, reassigning its value within the function is considered a side effect.

the output of the function won't always be the same for the same input. the function will always return num1 + 5, not just the sum of the two input parameters

Najmul-Hasan-Sobuj commented 8 months ago
function sum(num1, num2) {
  num2 = 5;

  return num1 + num2;
}

console.log(sum(1, 2)); // => 6
If an argument is mutated, does it remain a Pure Function or become a Non Pure Function?

In the provided JavaScript function, the argument num2 is mutated inside the function. This kind of mutation affects whether the function can be considered a "pure" function.

A pure function is one where the return value is only determined by its input values, without observable side effects. This means a pure function always returns the same output for the same inputs and does not cause any observable changes in the state of the program or its environment.

In your example, the function sum mutates its second argument (num2). Even though the mutation is confined within the scope of the function and does not affect the external environment, it still implies that the function's output is not solely determined by its original inputs.

Therefore, due to the internal mutation of the argument, this function would be considered a non-pure function. In pure functions, the inputs (arguments) should not be changed, and the function should not have any side effects outside its scope.