DEV Community

Discussion on: Functional Programming Principles in JavaScript

Collapse
 
architectak profile image
Ankit Kumar

const squareIt = (number) => {
    return number * number;
}
const myInput = { valueOf() { return performance.now() }}

console.log(performance.now()) // 132161.5
console.log(squareIt(myInput)) // 17466767811.611576
console.log(performance.now()) // 132162
console.log(squareIt(myInput)) // 17466847108.83685

Enter fullscreen mode Exit fullscreen mode

JS is fun, since input is changing its value on each call, hence output is different

Collapse
 
jonrandy profile image
Jon Randy ๐ŸŽ–๏ธ • Edited

But the input to the function is the same. The calculation differs because of coercion that happens as a feature if JS. The inputs themselves are unchanged. The input in this case is an object with a single method.

Thread Thread
 
architectak profile image
Ankit Kumar

In input of function is function that keeps changes its value, then that function can not be considered as pure function, right ?

Thread Thread
 
jonrandy profile image
Jon Randy ๐ŸŽ–๏ธ • Edited

The input is an object, but it's value upon coercion to a number differs on each coercion. In a very strict sense, such a simple function could be considered impure. To make it strictly pure in JS, you could add a bunch of code checking types etc.