함수

치로·2024년 8월 20일

1. 함수의 정의

function 함수 이름 () {
	... 실행할 구문 ...
}

2. 함수의 호출

함수 이름():

3. 파라미터가 있는 함수

function f(x, y) {

}

4. 파라미터가 있는 함수 호출

f(10, 2);
<!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>
    <script>
        function sayHello() {
            document.write("<h1>안녕하세요</h1>")
            document.write("<h1>자바스크립트</h1>")
        }
        sayHello();
        sayHello();
    </script>
</body>
</html>
<!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>
    <script>
        function f(x) {
            var y = x + 1;
            document.write("<h1>" + y + "</h1>");
        }
        f(2, 10);
        f(5);
        f(10);
    </script>
</body>
</html>
<!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>
    <script>
        function f(x, y){
            var z = x+y;
            document.write("<h1>" + z + "</h1>")
        }
        f(2);
        f(5, 10);
        
    </script>
</body>
</html>

5. 리턴형 함수

dunction f(x) {
	return x+1;
} 
var y = f(5);
  • 자바스크립트의 함수는 처리 도중 return문을 만나게 되면 그 즉시 실행을 중단
  • 이러한 특성을 이용하여 특정 조건이 충족되지 않을 경우 등에 대한 처리 중단을 목적으로 return문을 사용할 수 있으며, 리턴값이 없이 처리를 중단하고자 하는 경우에는 return 키워드만 사용
  • 이 때, 값이 없는 리턴 결과를 변수에 대입한 경우, 정의되지 않은 값인 "undefined"가 대입
<!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>
    <script>
        function getMember () {
            return 'javascript';
            
    }
    alert(getMember());
    </script>
</body>
</html>
<!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>
    <script>
        function f(x, y) {
            var z = x + y;
            if(z < 10) {
                return;
            }
            return z;
        }
        var a = f(2, 1);
        var b = f(5, 7);
        var c = f(10, 5);
       
        document.write("<h1>" + a + "</h1>");
        document.write("<h1>" + b + "</h1>");
        document.write("<h1>" + c + "</h1>");
    </script>
</body>
</html>

6. 익명 함수

    <!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>
        <script>
            // 익명 함수 : 일회성 호출
            (function() {
                i = 0;
                while(i<10) {
                    document.write(i);
                    i++;
                }
            })();
        </script>
    </body>
    </html>

7. 화살표 함수

  • 함수 표현식보다 단순하고 간결한 문법으로 함수를 만들 수 있는 방법
  • 매개변수의 지정
    () =>{...} // 매개변수가 없는 경우
    x => {...} // 매개변수가 한 개인 경우
    (x, y) => {...} // 매개변수가 여러 개인 경우
  • 함수 몸체 지정 방법
    x => {return x x}
    x => x
    x // 함수 몸체가 한 줄의 구문이라면 중괄호 생략 가능, 암묵적으로 return이 됨
<!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>
    <script>
        // 매개변수가 없는 경우
        // 괄호 생략 불가능
        var f = () => console.log('function');
        f();

        // 매개변수가 하나인 경우
        var f2 = x => console.log(x);
        f2('function2');

        // 매개변수가 여러 개인 경우
        // 간단하게 한줄 표현 {}와 return이 생략 가능
        // { return a + b } = a + b
        var f3 = (a, b) => a + b;
        console.log(f3(1, 3));

        // {}를 사용했는데 return이 없으면 return이 안됨
        var f4 = (a, b) => {return a + b};
        console.log(f4(2, 5));
    </script>
</body>
</html>
<!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>
    <script>
        var age = prompt("나이를 알려주세요", 19);
        var welcome = (age < 19) ? 
        () => alert('안녕') : () => alert('안녕하세요!');
        welcome();
    </script>
</body>
</html>

8. 콜백 함수

  • 함수의 파라미터로 함수를 넘기는 것
<!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>
    <script>
        function cry () {
            console.log("Action : cry")
        }

        function sing () {
            console.log("Action : sing")
        }
        function checkMood(mood) {
            if (mood == 'good') {
                sing();
            } else {
                cry();
            }
        }
        checkMood('good')
    </script>
</body>
</html>
<!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>
    <script>
        function cry () {
            console.log("Action : cry")
        }

        function sing () {
            console.log("Action : sing")
        }
        function checkMood(mood, goodCallback, badCallback) {
            if (mood == 'good') {
                goodCallback();
            } else {
                badCallback();
            }
        }
        checkMood('sad', sing, cry)
    </script>
</body>
</html>

0개의 댓글