Sobes.tech
Middle

What is a pure function? Is console.log inside a function a side effect?

sobes.tech AI

Answer from AI

A pure function is a function that always returns the same result given the same inputs and does not cause any side effects.

Side effects are any actions of a function that go beyond computing a value, such as:

  • modifying external variables or states,
  • performing input-output operations (e.g., writing to the console, working with files, network),
  • modifying the function's arguments.

console.log inside a function is a side effect because it outputs data to the console, affecting the external world and not directly related to the function's return value.

Example of a pure function:

function add(a, b) {
  return a + b;
}

Example of a function with a side effect:

function logSum(a, b) {
  const sum = a + b;
  console.log(sum); // side-effect
  return sum;
}

Thus, console.log inside a function makes it impure.

What is a pure function? Is console.log inside a… - sobes.tech