Pure Functions in Javascript

esphoenixc·2021년 12월 1일

Pure Function is a function (a block of code ) that always returns the same result if the same arguments are passed. It does not depend on any state, or data change during a program’s execution rather it only depends on its input arguments.

Also a pure function does not produce any observable side effects such as network requests or data mutation etc.

function calculateProduct( productPrice ) {
    return productPrice * 0.05;

The above function will always return the same result, if we pass the same productPrice. In other words, it’s output doesn’t get effected by any other values / state changes. So we can call “calculateGST” function as a Pure function.

var vat = 20;
function calculateProduct( productPrice ) {
    return productPrice * (vat / 100) + productPrice;

This is not a pure function as it relies on the external variable vat. even if we pass the same value for the productPrice, if the value of vat is somehow updated, then we would get a different output.

위에 함수는 순수함수가 아니다 왜냐하면 vat라는 변수에 값이 의존하고 있기 때문이다. 우리가 똑같은 값을 productPrice에 전달을 해도 vat 변수 값이 변하면 return 받는 output또한 바뀌기 때문이다.



0개의 댓글