함수 구현 연습
이 단계에서는 다양한 함수 기법을 보여주는 작은 프로그램을 만들어 함수 구현을 연습합니다. 함수 구현에 대한 이해를 강화하기 위해 간단한 계산기 애플리케이션을 구축할 것입니다.
WebIDE 를 열고 ~/project 디렉토리에 calculator.js라는 새 파일을 만듭니다. 몇 가지 수학 함수를 구현할 것입니다.
// Function to add two numbers
function add(a, b) {
return a + b;
}
// Function to subtract two numbers
function subtract(a, b) {
return a - b;
}
// Function to multiply two numbers
function multiply(a, b) {
return a * b;
}
// Function to divide two numbers with error handling
function divide(a, b) {
if (b === 0) {
return "Error: Division by zero";
}
return a / b;
}
// Function to calculate the square of a number
function square(x) {
return x * x;
}
// Demonstrate calculator functions
console.log("Addition: 5 + 3 =", add(5, 3));
console.log("Subtraction: 10 - 4 =", subtract(10, 4));
console.log("Multiplication: 6 * 7 =", multiply(6, 7));
console.log("Division: 15 / 3 =", divide(15, 3));
console.log("Square of 4 =", square(4));
console.log("Division by zero:", divide(10, 0));
이 코드를 실행하면 다음과 같은 출력이 표시됩니다.
Example output:
Addition: 5 + 3 = 8
Subtraction: 10 - 4 = 6
Multiplication: 6 * 7 = 42
Division: 15 / 3 = 5
Square of 4 = 16
Division by zero: Error: Division by zero
함수 구현에 대한 주요 사항:
- 명확하고 단일 책임이 있는 함수를 만듭니다.
- 매개변수를 사용하여 함수를 유연하게 만듭니다.
- 필요한 경우 오류 처리를 구현합니다.
- 다양한 입력을 사용하여 함수를 테스트합니다.
- 의미 있는 함수 및 변수 이름을 사용합니다.
더 많은 수학 함수를 추가하거나 기존 함수를 수정하여 실험해 보십시오.