What are pure functions in JavaScript?
Asked on Aug 08, 2024
Answer
Pure functions in JavaScript are functions that, given the same input, will always return the same output and do not produce any side effects. They are predictable and easier to test.
<!-- BEGIN COPY / PASTE -->
function add(a, b) {
return a + b;
}
console.log(add(2, 3)); // 5
console.log(add(2, 3)); // 5
<!-- END COPY / PASTE -->
Additional Comment:
✅ Answered with JavaScript best practices.- The "add" function is a pure function because it always returns the same result for the same inputs and does not modify any external state.
- Pure functions are easier to test and debug since they are predictable.
- They help in maintaining immutability and can be easily parallelized.
- Avoiding side effects means the function does not alter any external variables or states.
Recommended Links:
← Back to All Questions