Front-end/JavaScript
JS - Function(함수)
주술회전목마
2022. 10. 27. 01:44
❓why use Function?
To encapsulate a piece of code
function name(parameter1, parameter2) {
}
"Function 함수이름 () 순서"
- () : 함수를 실행 시킴
- 키워드로 시작하며 객체이다.
- 괄호()에는 쉼표(,)로 구분된 매개변수 이름이 포함
(parameter1, parameter2, ...)
- {} : 함수에 의해 실행될 코드
- 함수 호출
- 선언 (매개변수 parameter)
- 호출 (전달인자 argument)
- 함수 반환
return 명령문에 도달 시, 실행이 중지
var x = plus(4,3); //4, 3 -> argument
function plus(a, b) { //a,b -> parameter
return a + b; //7
}
- 즉시 실행 함수
객체(object) 안에서 매개변수가 argument를 받는 방식
const player = {
name: "chaeyoung",
sayHello: function(otherPlayerName) {
console.log("hello! " + otherPlayerName);
}
};
console.log(player.name); //chaeyoung
player.sayHello("jennie"); // hello! jennie
return vs console.log()
const age = 24;
function KrAge(ageOfForeigner) {
ageOfForeigner + 2;
return "hello";
}
const krAge = KrAge(age);
console.log(krAge); //hello
- return : 꺼내먹기 위함
- console.log() : 콘솔에 결과를 보여주기 위함 한마디로 그림의 떡