함수
함수 선언 방법 및 호출
- 매개변수[Parameter] : 함수 내부에서만 사용할 수 있는 변수
- 인자[Argument] : 함수 호출 시 매개변수에 들어갈 값
// 함수 선언
function 함수이름 (매개변수[Parameter]) {
// 함수가 호출되었을 때 실행할 코드
}
// 함수 호출
함수이름(인자[Argument]);
// 함수 선언 시 매개변수 초기값 지정
function 함수이름 (매개변수[Parameter] = 초기값) {
// 함수가 호출되었을 때 실행할 코드
}
// 함수 호출
함수이름(인자[Argument]);
함수 사용 이유
- 중복 코드를 피하기 위함
- 가독성을 높여줌
// 레드벨벳 멤버 이름 출력 [함수 미 사용]
let name = "주현";
console.log("이름 : " + name);
name = "슬기";
console.log("이름 : " + name);
name = "승완";
console.log("이름 : " + name);
name = "수영";
console.log("이름 : " + name);
name = "예림";
console.log("이름 : " + name);
// 레드벨벳 멤버 이름 출력 [함수 사용]
function redVelvet(name) {
console.log("이름 : " + name);
}
redVelvet("주현");
redVelvet("슬기");
redVelvet("승완");
redVelvet("수영");
redVelvet("예림");
함수 동작 원리
- Call Stack : 현재 실행 중인 기능을 추적하고, 계산을 수행한다.
- LIFO(Last In First Out) 방식으로 Stack에 저장된다.
function a() {
console.log("a 함수 호출");
b();
return 1;
}
function b() {
console.log("b 함수 호출");
c();
return 2;
}
function c() {
console.log("c 함수 호출");
return 3;
}
a();
함수의 호이스팅(Hoisting)
호이스팅(Hoisting)이란?
- 인터프리터가 변수와 함수의 메모리 공간을 선언 전에 미리 할당하는 것을 의미한다.
- 덕분에 함수를 호출하는 코드를 함수 선언보다 앞에 작성할 수 있다.
함수의 호이스팅(Hoisting)
showMessage();
function showMessage() {
let text = "javascript";
console.log("hello wolrd! " + text);
}
return문
- 함수가 실행 중에 return문을 만나면 함수 실행을 종료한다.
- 이때 return문 옆에 작성한 값을 함수를 호출한 지점으로 반환해 준다.
- return문 뒤에 값이 없으면 undefined를 반환한다.
- 함수에서 return문을 작성하지 않아도 기본으로 들어가 있다.
function showMessage() {
console.log("hello world! 1");
return;
console.log("hello world! 2");
}
console.log(showMessage()); // undefined
function showMessage() {
return "hello world";
}
console.log(showMessage()); // hello world
참조
- https://designer-ej.tistory.com/entry/Web-Call-Stack-자바스크립트의-콜스텍
- https://developer.mozilla.org/ko/docs/Glossary/Hoisting
- https://blog.bitsrc.io/master-javascript-call-by-sharing-parameter-passing-7049d65163ed
- https://cabulous.medium.com/javascript-execution-context-part-2-call-stack-and-multiple-execution-contexts-dbe428a94190
- https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Statements/return
'Javascript' 카테고리의 다른 글
[Javascript] 형 변환 (0) | 2022.11.03 |
---|---|
[Javascript] 다양한 함수 선언 방법 (0) | 2022.11.02 |
[Javascript] 변수와 상수 (0) | 2022.10.31 |
[Javascript] 연산자 (2) | 2022.10.28 |
[Javascript] Javascript란? (0) | 2022.10.28 |