JS

2024.07.19 JavaScript 핵심 JS - 점검 3(함수에 이해와 활용)

정훈5 2024. 7. 19. 10:20

 

학습 목표 

1. 함수에 선언과 사용 
2. 함수 표현식이란? 
3. 즉시 실행 함수란?
4. 화살표 함수란?

 

1. 함수에 선언과 사용

 index7.html

더보기

 index7.html

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

    <script>

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

        function addNumber(a, b) {
            let sum = a + b;
            return sum;
        };

        console.log(addNumber(10, 10)); // 결과 값 : 20

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

 

2. 함수 표현식이란?

자바스크립트에서 "함수 표현식"은 함수를 변수에 할당하는 방식으로 정의하는 것을 의미합니다.

함수 표현식은 함수를 값으로 다루는 함수형 프로그래밍의 개념 중 하나이며, 매우 유용한 패턴 중 하나입니다.

 

함수 자체가 식(Expression) 이기 때문에 함수를 변수에 할당하거나 함수의 매개변수로 사용할 수 도 있음 (일급 객체)

 

index8.html

더보기

index8.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>index8.html 파일 입니다.</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());

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

        console.log(time);

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

        function add2(x, y) {
            return x + y;
        }

        console.log(add(3, 5));
        console.log(add2(2, 2));

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

    </script>

</body>
</html>