자바스크립트 같은 스크립트 언어들은 우리가 공부한 강언어 형식의 문법보다 자유도가 크다.

따라서, 함수에서도 다양한 형태의 모습이 존재한다.

함수의 형태

일반적인 형태

<!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 addNumber(num1,num2){
            let sum= num1+num2; //지역변수
            return sum;
        }

let result = addNumber(2,3);
document.write(`두 수를 더한 값: ${result}`);

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

다양한 형태의 매개변수

<!DOCTYPE html>
<html lang="ko">
<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>함수</title>
	<style>
    body {
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      height: 100vh;
			font-size: 1.2em;
    }
	</style>
</head>
<body>
	<script>		
    // Do it! 매개변수 기본값 사용하기
    
		function multiple(a, b = 5, c = 10) { 	// b = 5, c = 10으로 기본값 지정
			return a * b + c;
		}
    
    let result1 = multiple(5, 10, 20);   // a = 5, b = 10, c = 20
    document.write(`multiple(5, 10, 20) = ${result1}<br>`);  //문자열내에 변수를 표현할 때 ${치환 } , `(백틱)을 사용한다.
    
    let result2 = multiple(10, 20);    // a = 10, b = 20, c = 10(기본값)
    document.write(`multiple(10, 20) = ${result2} <br>`);
   
    let result3 = multiple(30);        // a = 30, b = 5(기본값), c = 10(기본값)
    document.write(`multiple(30) = ${result3}`);

//매개변수의 갯수를 지정하지 않고 가변적으로 사용할때 ...연산자를 사용한다.
    function sum(...numbers){
      let total =0;
      for(let i=0;i<numbers.length;i++){
        total += numbers[i];
      }
      return  total;
    }
  console.log(sum(2,3,4,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>
        // 매개변수로 객체({name,age})가 들어갈수 있다.
    function createUser({name,age}){ //
        console.log(`이름 : ${name}, 나이:${age}`);
    }
    createUser({ name: "김철수", age: 30 });

    </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(){}() );

(
function(){
alert("즉시 실행 함수")
}()
);

(function(a,b){
sum = a+b;
}(100,200)
);

document.write("합계"+sum)
    </script>

</body>
</html>

익명함수( feat.화살표 함수)