Sobes.tech
Middle

Which function is pure? What are side effects?

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 modify any state outside its scope. It has no side effects.

Side effects are any changes to the state outside the function or interactions with the external world, such as:

  • Modifying global variables
  • Modifying arguments by reference
  • Input/output (writing to a file, printing to the console)
  • Making network requests

An example of a pure function in JavaScript:

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

It always returns the sum of a and b and does not change anything outside itself.

An example of a function with a side effect:

let counter = 0;
function increment() {
  counter += 1; // modifies external state
}

Understanding pure functions and side effects is important for predictability and testability of code, especially in functional programming and when working with React.

Which function is pure? What are side effects… - sobes.tech