개발자가 되

13기 혼공단(js)

[혼공JS] 4주차

dltjdud 2025. 2. 9. 21:52

실화인가요.. 개학이 한 달도 남지 않았다는 사실이.. 두렵습니다..

어뜨케...ㅠㅠ

 

익명 함수

function() { }

 

선언적 함수

function 함수() {
}

let 함수  = function () {} (동일함)

 

 

매개변수 리턴값 

function 함수(매개변수, 매개변수, 매개변수) {
    문장
    문장
    return 리턴값
}

 

기본적인 함수 예제

  • 윤년을 확인하는 함수 만들기
<html>
<head>
    <title>윤년인지 확인하는 함수</title>
</head>
    <script>
        function isLeapYear(year) {
            return (year % 4 === 0) && (year % 100 !== 0) || (year % 400 === 0)
        }

        console.log(`2020은 윤년일까? === ${isLeapYear(2020)}`)
        console.log(`2010은 윤년일까? === ${isLeapYear(2010)}`)
        console.log(`2000은 윤년일까? === ${isLeapYear(2000)}`)
        console.log(`1900은 윤년일까? === ${isLeapYear(1900)}`)
    </script>
<body>
</body>
</head>
</html>

 

  • A와 B까지 더하는 함수 만들기
<html>
<head>
    <title>a부터 b까지 더하는 함수</title>
</head>
    <script>
        function sumAll(a, b) {
            let output = 0
            for(let i = 1; i <= b; i++) {
                output += 1
            }
            return output
        }

        console.log(`1부터 100까지의 합 : ${sumAll(1, 100)}`)
        console.log(`1부터 500까지의 합 : ${sumAll(1, 500)}`)
    </script>
<body>
</body>
</head>
</html>

 

+ 숫자를 계산해서 출력할 깨는 이번 예제처럼 다음과 같은 형태의 함수를 사용합니다.

function 함수(매개변수) {
let output = 초기값
    처리한다
    return output
}

 

  • 최솟값 구하는 함수 만들기
<html>
<head>
    <title>최솟값을 구하는 함수</title>
</head>
    <script>
        function min(array) {
            let output = array[0]
            for(const item of array) {
                // 현재 output보다 더 작은 item이 있다면
                if(output > item) {
                    // output의 값을 item으로 변경
                    output = item
                }
            }
            return output
        }

        const testArray = [52, 273, 32, 103, 275, 24, 57]
        console.log(`${testArray} 중에서`)
        console.log(`최솟값 = ${min(testArray)}`)
    </script>
<body>
</body>
</head>
</html>

 

나머지 매개변수와 일반 매개변수 조합하기

function 함수 이름(...나머지 매개변수) { }

 

전개 연산자

함수 이름(...배열)

 

기본 매개변수

함수 이름(매개변수, 매개변수=기본값, 매개변수=기본값)

function sample(a=기본값, b) {}

 

콜백 함수

  • 콜백 함수를 활용하는 함수 : forEach()
    function (value, index, array) { }
<html>
<head>
    <title>배열 forEach() 메소드</title>
</head>
    <script>
        const number = [273, 52, 103, 32, 57]

        number.forEach(function (value, index, array) {
            console.log(`${index}번째 요소 : ${value}`)
        })
    </script>
<body>
</body>
</head>
</html>

 

  • 콜백 함수를 활용하는 함수 : map()
<html>
<head>
    <title>배열 map() 메소드</title>
</head>
    <script>
        // 배열을 선언합니다.
        let numbers = [273, 52, 103, 32, 57]

        // 배열의 모든 값을 제곱합니다.
        numbers = numbers.map(function(value, index, array) {
            return value * value
        })

        // 출력합니다.
        numbers.forEach(console.log)
    </script>
<body>
</body>
</head>
</html>

 

  • 콜백 함수를 활용하는 함수 : filter()
<html>
<head>
    <title>배열의 filter() 메소드</title>
</head>
    <script>
        const numbers = [0, 1, 2, 3, 4, 5]
        const evenNumbers = numbers.filter(function (value) {
            return value % 2 === 0
        })

        console.log(`원래 배열 : ${numbers}`)
        console.log(`짝수만 추출 : ${evenNumbers}`)
    </script>
<body>
</body>
</head>
</html>

 

화살표 함수

(매개변수) => {
}

(매개변수) => 리턴값
<html>
<head>
    <title>배열의 메소드와 화살표 함수</title>
</head>
    <script>
        // 배열 선언합니다.
        let numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

        // 배열의 메소드룰 연속적으로 사용합니다.
        numbers
            .filter((value) => value % 2 === 0)
            .map((value) => value * value)
            .forEach((value) => {
                console.log(value)
            })
    </script>
<body>
</body>
</head>
</html>

 

타이머 함수

함수 이름 설명
setTimeout(함수, 시간) 특정 시간 후에 함수를 한 번 호출합니다.
setInterval(함수, 시간) 특정 시간마다 함수를 호출합니다.
<html>
<head>
    <title>타이머 걸기</title>
</head>
    <script>
        setTimeout(() => {
            console.log('1초 후에 실행합니다.')
        }, 1 * 1000)

        let count = 0
        setInterval(() => {
            console.log(`1초마다 실행됩니다(${count}번째)`)
            count++
        }, 1 * 1000)
    </script>
<body>
</body>
</head>
</html>

 

함수 이름 설명
clearTimeout(함수, 시간) setTimeout() 함수로 설정한 타이머를 제거합니다.
clearInterval(함수, 시간) setInterval() 함수로 설정한 타이머를 제거합니다.

 

<html>
<head>
    <title>타이머 취소하기</title>
</head>
    <script>
        let id
        let count = 0
        id = setInterval(() => {
            console.log(`1초마다 실행됩니다.(${count}번째)`)
            count++
        }, 1 * 1000)

        setTimeout(() => {
            console.log('타이머를 종료합니다.')
            clearInterval(id)
        }, 5 * 1000)
    </script>
<body>
</body>
</head>
</html>

 

즉시 호출 함수

  • 이름 충돌 문제 발생
<html>
<head>
    <title>이름 충돌 문제 발생</title>
</head>
    <script>
        let pi = 3.14
        console.log(`파이 값은 ${pi}입니다.`
        )
    </script>
    <script>
        let pi = 3.141592
        console.log(`파이 값은 ${pi}입니다.`)
    </script>
<body>
</body>
</head>
</html>

 

  • 블록과 함수 블록을 사용해 이름 충돌 문제 해결하기
<html>
<head>
    <title>블록과 함수 블록을 사용해 이름 충돌 문제 해결하기</title>
</head>
    <script>
        let pi = 3.14
        console.log(`파이 값은 ${pi}입니다.`)

        // 블록을 사용한 스코프 생성
        {
            let pi = 3.141592
            console.log(`파이 값은 ${pi}입니다.`)
        }
        console.log(`파이 값은 ${pi}입니다.`)

        // 함수 블록을 사용한 스코프 생성
        function sample() {
            let pi = 3.141592
            console.log(`파이 값은 ${pi}입니다.`)
        }

        sample()
        console.log(`파이 값은 ${pi}입니다.`)
    </script>
<body>
</body>
</head>
</html>

즉시 호출 함수 문제 해결하기

  • 즉시 호출 함수를 사용한 문제 해결
<html>
<head>
    <title>즉시 호출 함수를 사용한 문제 해결</title>
</head>
    <script>
        let pi = 3.14
        console.log(`파이 값은 ${pi}입니다.`)
    </script>
    <script>
        (function () {
            let pi = 3.141592
            console.log(`파이 값은 ${pi}입니다.`)
        }) ()
    </script>
<body>
</body>
</head>
</html>

 

엄격 모드

<script>
	'use strict'
    문장 
    문장
</script>
  • 선언 없이 변수 사용
<html>
<head>
    <title>선언 없이 변수 사용</title>
</head>
    <script>
        data = 10
        console.log(data)
    </script>
<body>
</body>
</head>
</html>

 

    <script>
        (function() {
        	'use strictt'
            문장
            문장
        }) ()
    </script>

 

익명 함수와 선언적 함수의 차이

  • 익명 함수의 사용
<html>
<head>
    <title>익명 함수 호출</title>
</head>
    <script>
        // 변수를 선언합니다.
        let 익명함수

        // 익명 함수를 2번 생성합니다.
        익명함수 = function () {
            console.log('1번째 익명 함수입니다.')
        }
        익명함수 = function () {
            console.log('2번째 익명 함수입니다.')
        }

        // 익명 함수를 호출합니다.
        익명함수()
    </script>
<body>
</body>
</head>
</html>

 

  • 선언적 함수 호출
<html>
<head>
    <title>선언적 함수 호출</title>
</head>
    <script>
        // 선언적 함수를 호출합니다.
        선언적함수()

        // 선언적 함수를 2번 생성합니다.
        function 선언적함수() {
            console.log('1번째 선언적 함수입니다.')
        }
        function 선언적함수() {
        console.log('2번째 선언적 함수입니다.')
        }
    </script>
<body>
</body>
</head>
</html>

 

  • 선언적 함수와 익명 함수의 조합
<html>
<head>
    <title>선언적 함수와 익명 함수의 조합</title>
</head>
    <script>
        // 익명 함수를 생성합니다.
        함수 = function() {
            console.log('익명 함수입니다.')
        }

        // 선언적 함수를 생성하고 할당합니다.
        function 함수() {
            console.log('선언적 함수입니다.')
        }

        // 함수 호출합니다.
        함수()
    </script>
<body>
</body>
</head>
</html>

 

  • 블록이 다른 경우 선언적 함수의 사용
<html>
<head>
    <title>블록이 다른 경우 선언적 함수의 사용</title>
</head>
    <script>
        선언적함수()

        function 선언적함수() {
            console.log('1번째 선언적 함수입니다.')
        }
    </script>
    <script>
        function 선언적함수() {
            console.log('2번째 선언적 함수입니다.')
        }
    </script>
    <script>
        선언적함수()
    </script>
<body>
</body>
</head>
</html>

 

<html>
<head>
    <title>let 사용의 의미</title>
</head>
    <script>
        // 익명 함수를 생성합니다.
        let 함수 = function() {
            console.log('익명 함수입니다.')
        }

        // 선언적 함수를 생성하고 할당합니다.
        function 함수() {
            console.log('선언적 함수입니다.')
        }

        // 함수를 호출합니다.
        함수()
    </script>
<body>
</body>
</head>
</html>

+ git https://github.com/dltjdud-0225/13gi_hongong_js.git

 

 

기본 미션

p. 202 <윤년을 확인하는 함수 만들기> 예제를 실행하여 2022년이 윤년인지 확인하는 결과 인증하기

<html>
<head>
    <title>윤년인지 확인하는 함수</title>
</head>
    <script>
        function isLeapYear(year) {
            return (year % 4 === 0) && (year % 100 !== 0) || (year % 400 === 0)
        }

        console.log(`2020은 윤년일까? === ${isLeapYear(2020)}`)
        console.log(`2010은 윤년일까? === ${isLeapYear(2010)}`)
        console.log(`2000은 윤년일까? === ${isLeapYear(2000)}`)
        console.log(`1900은 윤년일까? === ${isLeapYear(1900)}`)
    </script>
<body>
</body>
</head>
</html>

 

선택미션

p. 240 확인 문제 1번 풀고, 풀이 과정 설명하기

<html>
<head>
    <title>선택미션</title>
</head>
    <script>
        // 변수를 선언합니다.
        let numbers = [273, 25, 75, 103, 32, 57, 24, 76]

        // 처리합니다.
        // (1) 홀수만 추출
        numbers =  numbers.filter((x) => x % 2 === 1)
        // (2) 100 이하의 수만 추출
        numbers = numbers.filter((x) => x <= 100)
        // (3) 5로 나눈 나머지가 0인 수만 추출
        numbers = numbers.filter((x) => x % 5 === 0)

        // 출력합니다.
        console.log(numbers)
    </script>
<body>
</body>
</head>
</html>
  1. 홀수만 추출
    조건: x % 2 === 1
    결과: [273, 25, 75, 103, 57]
    제거된 값: 32, 24, 76 (짝수)

  2. 100 이하의 수만 추출
    조건: x <= 100
    결과: [25, 75, 57]
    제거된 값: 273, 103 (100 초과)

  3. 5로 나눈 나머지가 0인 수만 추출
    조건: x % 5 === 0
    결과: [25, 75]
    제거된 값: 57 (5의 배수가 아님)

'13기 혼공단(js)' 카테고리의 다른 글

[혼공JS] 5주차  (1) 2025.02.16
[혼공JS] 3주차  (0) 2025.01.24
[혼공JS] 2주차  (0) 2025.01.19
[혼공JS] 1주차  (0) 2025.01.11