Pure Functions In JavaScript

Pure Functions In JavaScript

ยท

1 min read

A function is known as pure functions if it passes two tests:

๐Ÿฌ. ๐—ฆ๐—ฎ๐—บ๐—ฒ ๐—ถ๐—ป๐—ฝ๐˜‚๐˜๐˜€ ๐—ฎ๐—น๐˜„๐—ฎ๐˜†๐˜€ ๐—ฟ๐—ฒ๐˜๐˜‚๐—ฟ๐—ป ๐˜€๐—ฎ๐—บ๐—ฒ ๐—ผ๐˜‚๐˜๐—ฝ๐˜‚๐˜๐˜€

๐—˜๐˜…๐—ฎ๐—บ๐—ฝ๐—น๐—ฒ ๐Ÿ‘‡ const add = (x, y) => x + y;

add(2, 4); // 6

So it will always ๐—ฟ๐—ฒ๐˜๐˜‚๐—ฟ๐—ป ๐˜๐—ต๐—ฒ ๐˜€๐—ฎ๐—บ๐—ฒ ๐—ผ๐˜‚๐˜๐—ฝ๐˜‚๐˜ ๐—ถ๐—ณ ๐˜†๐—ผ๐˜‚ ๐—ฝ๐—ฎ๐˜€๐˜€ ๐Ÿฎ ๐—ฎ๐—ป๐—ฑ ๐Ÿฐ.

Nothing else affects the output.

๐Ÿญ. ๐—ก๐—ผ ๐˜€๐—ถ๐—ฑ๐—ฒ-๐—ฒ๐—ณ๐—ณ๐—ฒ๐—ฐ๐˜๐˜€

The side effect is any interaction with the outside world from within a function. It should not produce any side effects like No mutating input, Http Calls, etc.

So the ๐—ฑ๐—ฒ๐—ณ๐—ถ๐—ป๐—ถ๐˜๐—ถ๐—ผ๐—ป ๐—ผ๐—ณ ๐—ฝ๐˜‚๐—ฟ๐—ฒ ๐—ณ๐˜‚๐—ป๐—ฐ๐˜๐—ถ๐—ผ๐—ป๐˜€ would be:

The function always returns the same result if the same arguments are pass. It does not depend on any state, or data, change during a programโ€™s execution, and does not produce any observable side effects. It must only depend on its input arguments.

๐—˜๐˜…๐—ฎ๐—บ๐—ฝ๐—น๐—ฒ ๐Ÿ‘‡

const add = (x, y) => x + y;

add(2, 4); // 6

// It will always return the same output if you pass 2 and 4
ย