What is an Impure Function in JavaScript?

What is an Impure Function in JavaScript?

An impure function is a function that:

❌ Changes data outside its scope (side effects)
❌ Depends on external variables that can change
❌ Produces different outputs for the same input

Example:

let count = 0;

function increment() {
  count++;
  return count;
}

console.log(increment()); // 1
console.log(increment()); // 2

Why is this impure?

  • It modifies the external variable count.
  • Calling it multiple times gives different results even without arguments.

Another Example:

function getCurrentTime() {
  return Date.now();
}

This is impure because it returns a different value each time it runs.

Pure vs Impure

✅ Pure Function

function add(a, b) {
  return a + b;
}
  • Same inputs → Same output
  • No side effects

❌ Impure Function

let tax = 0.18;

function calculatePrice(price) {
  return price + price * tax;
}
  • Depends on external variable tax
  • If tax changes, the output changes

Interview Answer

An impure function is a function that either modifies external state, depends on external data, or causes side effects. It may return different results for the same input, making it harder to predict and test.

Related Interview Questions

🔹 What is a pure function in JavaScript?
🔹 What are side effects in JavaScript?
🔹 Why are pure functions preferred in React and functional programming?

Follow me @codebypc 🚀

JavaScript Booklet 1-10 by PC Prajapat

Leave a Reply

Your email address will not be published. Required fields are marked *