Pure Functions in JavaScript: Consistent Results without Side Effects

Do you know what is a pure function in JavaScript? When a function does not depend on external data or does not modify the external data then it's known as a pure function. Take a look at the below code: function add(a, b) { return a + b; } This add function is a pure function because it does not depend on any outside variable. It just uses the function parameters and returns a value based on some calculation. So when we call the function with the same arguments again and again we get the same result like this: add(10, 22); // 32 add(10, 22); // 32 That's why it's called a pure function. let sum = 0; function add(a, b) { sum = a + b; return sum; } The above function is not a pure function because even though we're not using the outside value in calculation we're changing the value which is defined outside the function(sum) Creating pure functions ensures that you get a consistent and predictable result without causing any side effects. If you're a React developer then you might know that reducer in redux is a pure function because it just uses the value of state and action and returns a new state without changing the original state. Also, every component you create in React has to be a pure component which means it should not manipulate or change any of the variables declared outside that component. 𝗙𝗼𝗿 𝗺𝗼𝗿𝗲 𝘀𝘂𝗰𝗵 𝘂𝘀𝗲𝗳𝘂𝗹 𝗰𝗼𝗻𝘁𝗲𝗻𝘁, 𝗱𝗼𝗻'𝘁 𝗳𝗼𝗿𝗴𝗲𝘁 𝘁𝗼 𝗳𝗼𝗹𝗹𝗼𝘄 𝗺𝗲. #javascript #reactjs #nextjs #webdevelopment

To view or add a comment, sign in

Explore content categories