JavaScript Interview Question #178
What are side effects in JavaScript?
Advanced JavaScript, Practical Problems & Senior Interview Scenarios Senior Advanced
Quick Interview Answer
A side effect is an observable interaction beyond returning a value. Examples include modifying global state, mutating an external object, changing the DOM, writing storage, logging, making a network request, or starting a timer.
Detailed Explanation
A side effect is an observable interaction beyond returning a value. Examples include modifying global state, mutating an external object, changing the DOM, writing storage, logging, making a network request, or starting a timer.
Side effects are necessary in useful applications, but keeping them explicit and localized makes code easier to test and maintain. Functions that both calculate values and perform unrelated side effects are often harder to reason about.
Code Example
function saveMessage(message) {
localStorage.setItem("message", message); // side effect
}
function formatMessage(message) {
return message.trim().toUpperCase(); // pure calculation
}
saveMessage(formatMessage(" hello "));