Marcin Kowal
Marcin Kowal

Reputation: 73

Can a function which returns a new object be considered "pure"?

Given the definition:

A pure function is a function which given the same input, will always return the same output and produces no side effects.

Can we consider function AmIPure as pure function? According to definition no, but I want to make sure.

function Amount(value, currency) {
  this.value = value;
  this.currency = currency;
}

function AmIPure(value, currency) {
  return new Amount(value, currency);
}

var foo = AmIPure(5, "SEK");
var baz = AmIPure(5, "SEK");
console.log(foo === baz); //false

Upvotes: 4

Views: 577

Answers (2)

Damiano
Damiano

Reputation: 811

It depends on the definition of "same".

If you expect strict object equality, then only functions returning scalars (e.g. numbers, booleans, ...) could ever be considered "pure".

In general, though, that's not what you really mean: you don't usually care if you get the exact same instance of an object, only if it is equal to another according to some definition, e.g.:

  • if they are strings with equal characters ("HELLO" and "HELLO")
  • if they are simple object with equal attribute names and values ({x:0,y:1} and {y:1,x:0})
  • if they are arrays with equal elements in the same order ([1,2,3] and [1,2,3])
  • ...

Upvotes: 5

Vineesh
Vineesh

Reputation: 3782

Here the result you are returning from the function is an object. If you compare the objects it won't give true. Instead you can compare the values

var foo = AmIPure(5, "SEK");
var baz = AmIPure(5, "SEK");
console.log(foo.value === baz.value && foo.currency === baz.currency ); 

This should give true.

Upvotes: -1

Related Questions