[JS] 함수 - 매개변수, return값(+ 연습)

happyyeom·2024년 10월 21일

매개변수

3과 5를 더해 출력하는 함수를 만들었다. 여기서 우리가 넣는 값에 따라서 그 값을 더해주는 것을 만들기 위해 매개변수라는 것을 사용할 수 있다.

console.clear();
function plus(a, b){
	console.log(a + b);
}

이렇게 괄호 안에 변수를 집어넣을 공간을 만들어주고 (선언하지 않아도 된다.)

plus(5, 4);
plus(1, 2);

이렇게 변수 자리에 값을 집어넣으면
매개변수는 함수로 전달되어 함수의 변수 자리에 들어가 코드를 실행하게 된다 .

return 값

매개 변수가 자판기(함수)를 사용하기 위한 동전이라면 return값은 자판기가 끝나고 나온 것, 즉 함수가 끝난 자리에 남는 값이라고 할 수 있다. 함수 안에

console.clear();
function plus(a, b) {
  return a + b;
}

이렇게 하면 이 함수가 끝난 자리에는 a + b 가 남는 것이다. 함수의 return값을 변수에 넣어서 출력해보자.


매개 변수 연습

매번 다르게 인사하는 함수

입력하는 언어 이름에 따라 그 언어로 인사를 출력하는 함수를 구현해보자.

console.clear();

function hello(a) {
    if(a == "한국어"){
        console.log("안녕하세요");
    }
    else if(a == "일본어"){
        console.log("곤니찌와");
    }
    else if(a == "영어"){
        console.log("헬로");       
    }
}

hello(한국어);
hello(일본어);
hello(영어);

매개변수 없이 다르게 인사하는 함수

console.clear();

var mode = 0;

function hello() {
    mode++;
    var hi
    if ( mode % 3 == 1 ) {
        hi = "안녕하세요";
    }
    else if ( mode % 3 == 2 ) {
        hi = "곤니찌와";
    }
    else {
        hi = "헬로";
    }
    
    console.log(hi);
}

hello();
hello();
hello();
hello();
hello();
hello();
hello();
hello();
hello();

여기서 함수 밖에서 선언된 변수 mode전역변수,
함수 안에서 선언된 변수 hi를 그 함수 내에서만 사용할 수 있는 지역변수라고 한다.

입력한 횟수대로 입력한 언어의 인사를 출력하는 방법

console.clear();


function hello(언어, 인사횟수) {
  var hi;
  
  if(언어 == "한국어"){
    hi = "안녕하세요";
  }
  else if(언어 == "일본어"){
    hi = "곤니찌와";
  }
  else if(언어 == "영어"){
    hi = "헬로";
  }
  for(let i = 0;i < 인사횟수; i++){
    console.log(hi);
  }
}

hello("영어", 2);
hello("한국어", 5);
hello("일본어", 6);

a의 단을 b단까지 출력하는 함수

console.clear();
function printDan(a, b) {
    console.log("== " + a + "단 출력 ==");
    let i;
    for(i = 1; i <= b; i++){
        console.log(a + " * " + i  + " = " + a * i);
    }
}

printDan(3, 3);
printDan(2, 9);


return값 연습

사칙연산 함수

console.clear();
function plus(a, b){
    let num = a + b;
    return num;
}
function minus(a, b){
    return a - b;
}
function mul(a, b){
    return a * b;
}
function div(a, b){
    return a / b;
}
let rs1 = plus(5,3);
let rs2 = minus(10,3);
let rs3 = mul(3,10);
let rs4 = div(10,5); 
    
console.log(rs1);
console.log(rs2);
console.log(rs3);
console.log(rs4);

profile
🌳🌳🌳🌳🌳🌳🌳🌳🌳🌳🌳🌳🌳🌳

0개의 댓글