Skip to main content

Command Palette

Search for a command to run...

Pure Functions In JavaScript

Published
โ€ข1 min readโ€ขView as Markdown
Pure Functions In JavaScript
Y

An engineer by profession and a JavaScript Lover by heart.

First and foremost, I love writing code. Ever since writing my first program in C and manipulating it to produce the desired output. I believe in the power of programming to transform and improve the lives of people around the world.

My curiosity levels are as fresh as when I was a child. I believe in eternal learning and deliberate effort as they are the only way to become the smartest in the room. I am a good timekeeper, always willing to learn new skills and use them in real-life problems.

An ambitious individual with a desire to succeed. A Cricket fanatic. A student who likes to take risks and does not shy away from experimenting with various combinations in life. Striving to do a lot. Wish me good luck ๐Ÿ™๐Ÿผ

My primary interest is in Web Development and Mobile Application Development.

Tech Stack:- ReactJS, NextJS, NodeJS, MongoDB, GraphQL, Javascript Version Control:- Git, Gitlab

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

More from this blog

Yash Mantri

20 posts

An engineer by profession and a JavaScript Lover by heart