Pure Functions in JavaScript
자바스크립트의 순수 함수
Last Updated :
17 Dec, 2024
마지막 업데이트 : 2024년 12월 17일
마지막 업데이트 : 2024년 12월 17일
Improve 개선
A Pure Function is a function (a block of code) that always returns the same result if the same arguments are passed.
순수 함수는 동일한 인수가 전달되면 항상 같은 결과를 반환하는 함수(코드 블록)입니다.
- Pure functions return consistent results for identical inputs.
순수 함수는 동일한 입력에 대해 일관된 결과를 반환합니다. - They do not modify external states or depend on mutable data.
외부 상태를 변경하지 않으며 변경 가능한 데이터에 의존하지 않습니다. - Often used with immutable data structures to ensure reliability.
신뢰성을 보장하기 위해 종종 불변 데이터 구조와 함께 사용됩니다. - Their independence from external states makes them highly reusable.
외부 상태로부터 독립적이기 때문에 재사용성이 매우 높습니다.
function add(a, b) {
return a + b;
}
console.log(add(2, 3));
console.log(add(2, 3));
5
1
function add(a, b) {
2
return a + b;
3
}
4
console.log(add(2, 3));
5
console.log(add(2, 3));
Output 출력
5 5
- It always returns the same result for the same input.
동일한 입력에 대해 항상 동일한 결과를 반환합니다. - It does not modify any external variables or state.
외부 변수나 상태를 변경하지 않습니다.
Note: Generally, we use the Pure function in JavaScript for any purpose.
참고: 일반적으로 JavaScript에서 어떤 목적으로든 순수 함수를 사용합니다.
Characteristics of Pure Functions
순수 함수의 특징들
- Deterministic Output: For a given set of inputs, the output is always the same.
결정론적 출력: 주어진 입력 집합에 대해 출력은 항상 동일합니다. - No Side Effects: The function does not:
부작용 없음: 함수는 다음을 수행하지 않습니다:- Modify variables outside its scope.
자신의 범위 밖에 있는 변수를 수정하지 않습니다. - Interact with external systems like APIs, databases, or DOM manipulation.
API, 데이터베이스 또는 DOM 조작과 같은 외부 시스템과 상호작용하지 않습니다. - Change mutable data. 변경 가능한 데이터를 변경합니다.
- Modify variables outside its scope.
- Immutability: Pure functions do not change the input values; instead, they return a new value or object.
불변성: 순수 함수는 입력 값을 변경하지 않고, 대신 새로운 값이나 객체를 반환합니다.
Example of a Function with Side Effects
부작용이 있는 함수의 예
Here, increment is not a pure function because it modifies the external variable count.
여기서 increment는 외부 변수 count를 수정하기 때문에 순수 함수가 아닙니다.
let c = 0;
function inc() {
c++;
return c;
}
console.log(inc());
console.log(inc());
8
1
let c = 0;
2
3
function inc() {
4
c++;
5
return c;
6
}
7
console.log(inc());
8
console.log(inc());
Output 출력
1 2
Impure Functions: What to Avoid
불순 함수: 피해야 할 것들
Impure functions produce unpredictable results or affect external states, which can lead to bugs and make your code harder to test.
불순 함수는 예측할 수 없는 결과를 생성하거나 외부 상태에 영향을 미쳐 버그를 유발하고 코드를 테스트하기 어렵게 만듭니다.
let user = { name: "Meeta", age: 25 };
function updated(newAge) {
user.age = newAge;
return user;
}
console.log(updated(26));
// Alters the global `user` object
console.log(user.age);
10
1
let user = { name: "Meeta", age: 25 };
2
3
function updated(newAge) {
4
user.age = newAge;
5
return user;
6
}
7
8
console.log(updated(26));
9
// Alters the global `user` object
10
console.log(user.age);
Output 출력
{ name: 'Meeta', age: 26 } 26
Real-World Applications of Pure Functions
순수 함수의 실제 적용 사례
- Data Transformation: Use pure functions in map, filter, and reduce operations for processing data.
데이터 변환: 데이터 처리를 위해 map, filter, reduce 연산에서 순수 함수를 사용하세요. - State Management: Libraries like Redux emphasize pure functions for state updates.
상태 관리: Redux와 같은 라이브러리는 상태 업데이트를 위해 순수 함수를 강조합니다. - Unit Testing: Pure functions are ideal for unit tests because they have predictable outputs.
단위 테스트: 순수 함수는 예측 가능한 출력을 가지므로 단위 테스트에 이상적입니다. - Performance Optimization: Pure functions are easily memoized, as their outputs depend solely on inputs.
성능 최적화: 순수 함수는 출력이 입력에만 의존하므로 쉽게 메모이제이션할 수 있습니다.