Sobes.tech
Middle

What is the difference between OOP and functional programming? What is a pure function?

sobes.tech AI

Answer from AI

Object-Oriented Programming (OOP) and Functional Programming are different programming paradigms with different approaches to organizing code.

OOP:

  • The main building block is an object, which combines data (properties) and behavior (methods).
  • Uses inheritance, encapsulation, polymorphism.
  • The state of objects can change (mutability).

Functional Programming:

  • The main building block is functions as "first-class objects".
  • Prefers pure functions that have no side effects and do not modify external state.
  • Uses immutability of data and function composition.

Pure function — a function that:

  • Always returns the same result for the same inputs.
  • Does not modify external state (has no side effects).

Example of a pure function:

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

Example of a impure function:

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