Function
Function
A reusable block of code. Takes input (parameters) and produces output (return value).
Function
A reusable block of code. Takes input (parameters) and produces output (return value).
A function in programming is an independent block of code that performs a specific task. It receives input values (parameters), processes them, and returns a result (return value), and once defined, it can be called repeatedly from multiple places.
Functions are the most fundamental way to improve code reusability. Instead of writing the same logic multiple times, defining it as a function reduces code duplication, and when a change is needed, you only have to modify one place. This greatly improves maintainability.
Functions are a core tool of abstraction. When complex logic is wrapped in a function with a meaningful name, code readability improves, and other developers can use it by looking only at the function name and parameters, without knowing the internal implementation.
In modern programming, functions are treated as first-class citizens, so they can be assigned to variables, passed as arguments to other functions, or used as return values. Functional Programming, which makes use of this characteristic, is widely used as a paradigm for writing code that reduces side effects and is easy to test.
// 1. 기본 함수 정의와 호출
function greet(name) {
return `안녕하세요, ${name}님!`;
}
console.log(greet("철수")); // 출력: 안녕하세요, 철수님!
// 2. 매개변수와 반환값
function calculateArea(width, height) {
const area = width * height;
return area;
}
const result = calculateArea(10, 5);
console.log(`면적: ${result}`); // 출력: 면적: 50
// 3. 기본값 매개변수 (Default Parameters)
function createUser(name, role = "user", active = true) {
return { name, role, active, createdAt: new Date() };
}
const admin = createUser("관리자", "admin");
const guest = createUser("게스트"); // role="user", active=true 기본값 사용
// 4. 화살표 함수 (Arrow Function)
const add = (a, b) => a + b;
const square = x => x * x;
const numbers = [1, 2, 3, 4, 5];
const doubled = numbers.map(n => n * 2); // [2, 4, 6, 8, 10]
// 5. 고차 함수 (Higher-Order Function)
function createMultiplier(factor) {
return function(number) {
return number * factor;
};
}
const double = createMultiplier(2);
const triple = createMultiplier(3);
console.log(double(5)); // 출력: 10
console.log(triple(5)); // 출력: 15
// 6. 콜백 함수 활용
function processData(data, onSuccess, onError) {
try {
const processed = data.map(item => item.toUpperCase());
onSuccess(processed);
} catch (error) {
onError(error.message);
}
}
processData(
["hello", "world"],
result => console.log("성공:", result),
error => console.log("실패:", error)
);
// 출력: 성공: ["HELLO", "WORLD"]
"This logic is repeated in three places. If we extract it into a utility function and reuse it, we reduce code duplication, and when we need to change it later, we only have to fix one place."
"A pure function always returns the same output for the same input and does not change external state. Such functions are easy to test and predictable, so I try to write them as pure functions whenever possible."
"This function is doing too much. Following the single responsibility principle, if we separate the data validation and storage logic into separate functions, testing becomes easier and reusability improves too."
Take a mock interview on this topic → WIA SOOM AI Interview · Start for free
When a single function exceeds 100 lines or does several things, it is hard to understand. If a function name contains "and", it is a sign that it needs to be split. Design each function to do only one thing.
Modifying global variables or changing external state inside a function makes bugs hard to trace. Whenever possible, favor pure functions that calculate and return results from their inputs alone.
A function name should start with a verb and clearly show what it does. Specific names like `validateEmail()` and `calculateTotalPrice()` improve code readability more than `process()`.