return의 두 가지 기능

Joah·2022년 5월 27일
0

Javascript

목록 보기
1/16

1. 함수에서 return을 만나면 함수는 종료된다.

function sayhello(){
	const name = "Joah";
    const introduce = "This is ";
  	console.log(introduce + name);
  	return;
  	console.log("Hello World " + introduce + name);
}
sayhello()
// This is Joah  => 콘솔 출력결과

코(드)풀이

함수는 함수 안에서 return을 만나면 함수를 바로 종료한다.
따라서 return 다음에 있는 실행문은 실행되지 않는다.
실행 결과를 보면 return문 다음의 console.log문은 실행되지 않는 것을 확인할 수 있다.




2. 함수의 결과값을 반환하여 호출문에 할당한다.

function sayhello(name) {
	const userName = name;
  	const introduce = "This is ";
  	return "Hello World " + introduce + userName
}
sayhello("Joah");
sayhello("Sasha");
sayhello("Riku");
sayhello("Dolche");

코(드)풀이

sayhello()는 함수를 호출하는 호출문이다.
괄호 안에 인자를 넣어준다. "Joah", "Sasha", "Riku", "Dolche" => 이 친구들이 인자(argument)
argument 친구들이 sayhello함수의 매개변수 name을 통해 함수 안에서 name에 할당된다.
그럼 sayhello() 함수는 return "Hello World " + introduce + userName값을 반환하는데, 함수를 호출문에 해당 return 값을 할당하게 된다.

console.log(sayhello("Joah")); //"Hello World This is Joah"
console.log(sayhello("Sasha")); //"Hello World This is Sasha"
console.log(sayhello("Kimi")); //"Hello World This is Kimi"
console.log(sayhello("Dolche")); //"Hello World This is Dolche"

위의 호출문을 console에 출력하면 해당 결과들이 출력된다. 즉, 호출문 자체에 return값이 할당되어 있으니 호출문을 직접 출력해도 sayhello함수의 return 값을 받을 수 있게된다.
그렇다면! 함수 호출문에 값이 할당되어 있다면, 호출문을 변수에 담아 변수를 console에 찍어보면 어떤 값이 나올까?

const joah = sayhello("Joah")
const sasha = sayhello("Sasha")
const kimi = sayhello("Kimi")
const dolche = sayhello("Dolche")
console.log(joah, sasha, kimi, dolche )
/*"Hello World This is Joah"
"Hello World This is Sasha"
"Hello World This is Kimi"
"Hello World This is Dolche"*/

각각의 호출문들은 이미 sayhello함수의 값을 담고 있기 때문에 변수에 할당하여 console에 나타내어도 똑같은 결과를 출력한다.


profile
Front-end Developer

0개의 댓글