educative.io

How the below function is pure?

how the below function is pure → in my opinion , every time we pass in the car object as an argument in accelerate(), it returns us an new object and an object is a non-primitive datatype and it makes comparison based on references. so, every time accelerate() is returning us a new object (references different for everyone) , That’s ,makes it a impure function ( on same input , we got different output) .
so how that function is pure(told in the course)? plz explain…
var car = { speed: 0, seats: 5 };

function accelerate(car) {

car.speed += 1;

return car;

}

console.log(accelerate(car));

console.log(accelerate(car));
console.log(accelerate(car) === accelerate(car)) //false


Course: https://www.educative.io/courses/react-beginner-to-advanced
Lesson: Pure Functions in Detail - React Deep Dive: From Beginner to Advanced

Hi @rishabh_jain, Thanks for reaching out to us.
Unfortunately, you misunderstood the example, the following code is not an example of a pure function.

var car = { speed: 0, seats: 5 };

function accelerate(car) {
  car.speed += 1;
  return car;
}

console.log(accelerate(car));
console.log(accelerate(car));

It is clearly mentioned in the lesson that it is an example of impure functions. For reference, I have attached the screenshot here.

Hope this helps!
Happy Learning :slight_smile:

Sorry but I paste the wrong code .
Below is the correct one . Plz have a look and explain me. Explanation is same as I described above .

var car = { speed: 0 };

function accelerate(car) {
return {
speed: car.speed + 1,
};
}

console.log(accelerate(car));
console.log(accelerate(car));

Hi @rishabh_jain
The following code has a function that takes in an object with parameters as its input. To ensure this function is pure, we must ensure that our values are not modified and are made into a new object before returning. In other words, entry values should not be modified.

var car = { speed: 0 };

function accelerate(car) {
  return {
    speed: car.speed + 1,
  };
}

console.log(accelerate(car));
console.log(accelerate(car));

This example describes that it’s pure! Same input, same output. You can see the output in the following screenshot as well.

Hope this will clear your confusion :slight_smile:
Thanks!

To fulfill the conditions of pure function -

  1. For same input , we got same output .
    But in this example , we are always getting different output . ( always return the new object every time)
    Isn’t it violates the rule of pure function

@rishabh_jain
The given example doesn’t violate the rule of pure function as clearly it’s pure! Same input, same output. Secondly, to ensure this function is pure, we must ensure that our values are not modified and are made into a new object before returning.

Hope it helps.
Thanks!