JS

함수의 이해와 활용

ryeonng 2024. 7. 19. 11:04

함수의 선언과 사용

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <h2>index7.html 파일입니다.</h2>
    <script>

        /**
        * 매개변수(parameter)
        * 함수를 선언하기 위해 필요하다고 지정하는 값.
        * 함수를 선언할 때, 함수 이름 옆의 괄호 안에 매개변수를 넣는다.
        * 
        * 인수(argument)
        * 함수를 실행하기 위해 필요하다고 지정하는 값
        * 함수를 실행할 때, 매개변수를 통해서 넘겨 주는 값을 인수라 한다.
        */

        function addNumber(a,b) { // 함수 선언 (데이터 타입 x)
            let sum = a + b;
            return sum;
        }

        console.log(addNumber(10,10));


    </script>
</body>
</html>

 

 

함수 표현식

자바스크립트에서 "함수 표현식"은 함수를 변수에 할당하는 방식으로 정의하는 것을 의미한다. 함수 표현식은 함수를 값으로 다루는 함수형 프로그래밍의 개념 중 하나이며, 매우 유용한 패턴 중 하나이다.

함수 자체가 식(Expression) 이기 때문에 함수를 변수에 할당하거나 함수의 매개변수로 사용할 수 도 있음 (일급 객체)
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <h1>index8.html 파일입니다.</h1>
    <script>

        // 1. 매개 변수가 없는 함수 표현식을 정의해보자.
        const currentTime = function() {
            const now = new Date();
            return now.toLocaleTimeString();
        };

        // 출력 결과의 차이를 잘 확인해보자.
        console.log(currentTime);
        console.log(currentTime());

        // 주의 ! 결과 분석을 통해 이해해보자.
        const time = currentTime();
        console.log('--------------------------');
        console.log(time);

        // 2. 
        const add = function(x,y) {
            return x + y;
        };
        console.log(add(3,5));

        const result = add(10,20);
        console.log(result);


    </script>
</body>
</html>

'JS' 카테고리의 다른 글

Browser Object Model  (0) 2024.07.23
Document Object Model  (0) 2024.07.23
객체와배열  (0) 2024.07.19
데이터 타입 및 연산  (0) 2024.07.18
사전 기반 지식  (0) 2024.07.18