본문 바로가기
Programming Language/JavaScript

[JavaScript] 순수함수 / 비순수함수 (함수형 프로그래밍)

by Baest 2022. 6. 7.

※본 포스팅은 개인 학습을 목적으로 작성된 것이므로 정확하지 않은 정보가 포함되어 있을 수 있음을 참고 부탁드립니다.


 

코드리뷰를 받으면서 언급된 순수함수에 대해서 알아보기로 했다. 🧐 

 

1. 순수함수 

우선 깔끔하게 위키를 던져본다. 크게 두 가지로 순수 함수에 대해 정의했다.

1) the function return values are identical for identical arguments (no variation with local static variablesnon-local variables, mutable reference arguments or input streams)

👉 들어온 인자가 같을 경우 결과(return)가 항상 같은 함수

 

2) the function application has no side effects (no mutation of local static variables, non-local variables, mutable reference arguments or input/output streams)

👉외부 상태를 변경하거나 외부의 영향을 받지 않는 함수

 

WIKI:https://en.wikipedia.org/wiki/Pure_function#:~:text=In%20computer%20programming%2C%20a%20pure,arguments%20or%20input%20streams)%2C%20and

 

Pure function - Wikipedia

From Wikipedia, the free encyclopedia Jump to navigation Jump to search Program function without side effects and which returns identical values for identical arguments In computer programming, a pure function is a function that has the following propertie

en.wikipedia.org

 

// JS

function add(a, b) { // 동일한 인자를 주면 동일한 결과를 리턴
	return a + b
}

 

2. 비순수함수

👉 함수 외부 상태에 의존하거나 상태에 따라 return 값이 달라지는 함수

 

// C++

int f() { // because of return value variation with a non-local variable
  return x;
}

// JS

let a = 5; // a의 값에 따라 add 함수의 return 값이 달라질 수 있음
function add(b, c) {
	return a + b + c
}

 

JS 예시 코드를 실행해 보았음

 

 

📚 함수형 프로그래밍: side effect를 없애고 순수 함수를 만들어 모듈화 수준을 높이는 프로그래밍 패러다임