2. đź«€Pure Function & Impure Function,Side Effects In Javascript
# Pure Function in JavaScriptđź’ˇ
A pure function is a function that meets the following criteria:
- Deterministic: For the same input, it always returns the same output.
- No Side Effects: It doesn’t modify external variables or states.
Example of a Pure Function
function add(a, b) {
return a + b; // No external dependencies or state changes
}
- Deterministic:
add(2, 3)
will always return5
. - No Side Effects: It doesn’t alter any external variables or data.
// PURE FUNCTION
//Those fuction which are deterministic in nature
function areaOfRectangle(length, width) {
return length * width;
}
console.log(areaOfRectangle(10, 20)); // Output: 200
console.log(areaOfRectangle(10, 20)); // Output: 200
Deterministic: For the inputs 10
and 20
, the function will always return 200
.
No Side Effects: The function does not modify any external variables or rely on them. It only uses the provided inputs (length
and width
).
# Impure Function in JavaScriptđź’ˇ
An impure function either:
- Depends on external states or variables.
- Modifies external variables or states.
- Produces unpredictable results due to reliance on external factors.
Example of an Impure Function
let count = 0;
function increment() {
count++; // Modifies an external variable
return count;
}
- Depends on External State: The output depends on the current value of
count
. - Side Effect: It modifies the external variable
count
.
// IMPURE FUNCTION
function test(length, width) {
const temp = Math.floor(Math.random() * 10); // Generates a random number
return length * width * temp;
}
console.log(test(10, 20)); // Output varies
console.log(test(10, 20)); // Output varies
console.log(test(10, 20)); // Output varies
Why This is an Impure Function:
- Non-Deterministic Behavior:The function uses
Math.random()
to generate a random value, so the output is unpredictable even for the same inputs. - Side Effects:Although this function does not directly modify external variables, it introduces unpredictability through reliance on
Math.random()
.
# Side Effectsđź’ˇ
A side effect occurs when a function interacts with or modifies something outside its local scope. This can include:
- Modifying a global variable.
- Changing a passed-in object or array.
- Making an HTTP request.
- Writing to a file or database.
- Logging output to the console.
Example of a Function with Side Effects
let globalVariable = 10;
function addToGlobal(value) {
globalVariable += value; // Modifies an external variable
}
Why Avoid Side Effects in Pure Functions?
- They make debugging harder.
- They reduce code reusability.
- They increase unpredictability in larger applications.
Key Differences Between Pure and Impure Functions
Pure Function =>
- Always returns the same output for the same input.
- No Side Effects.
- Does not rely on external state.
Impure Function =>
- Output may vary for the same input.
- Can have Side Effects.
- May depend on or modify external state.
Question 1
let output = console.log('Welcome to uncommon geek');
console.log('Output is ' + output); //Output is undefined
Explanation:
console.log
is a function in JavaScript- The
console.log()
function is used to print information to the console but does not return any value. Its return value isundefined
. - Hence,
output
will beundefined
, and the secondconsole.log
will print “Output is undefined”
Question 2
function areaOfRectangle(length, breadth) {
console.log('Area is ' + length * breadth); // This causes a side effect
return length * breadth;
}
areaOfRectangle(2, 4);
- Is it a pure function?
- No, it is not a pure function.
- Why? The
console.log
statement inside the function causes a side effect by modifying the external environment (the console). - To make it pure, remove the
console.log
statement:
function areaOfRectangle(length, breadth) {
return length * breadth; //Pure function
}
Question 3
const words = ['spray', 'destruction'];
const result = words.filter(word => word.length > 6);
console.log(result);
- Is
.filter()
a pure function? - Yes,
.filter()
is a pure function. - Why? It does not modify the original
words
array. Instead, it creates a new array (result
) based on the condition in the callback function. - Output:
['destruction']
Question : Why Pure Functions Are Essential ?
Deterministic:Pure functions always produce the same output for the same inputs, which makes the code predictable and easier to debug.
Memoization: Since pure functions are deterministic, their results can be cached. This improves performance by avoiding repeated computations for the same inputs.