특정 작업을 수행하는 코드 (하나의 모듈)
한번 선언하면 여러번 호출하여 사용할 수 있음
function(){}
// 또는
() => {}
function a(){}// 1. 함수 선언문 방식
const b = function(){}; // 2. 함수 표현식 방식
const c = () => {}; // 3. 화살표 함수 방식
2,3은 상수 또는 변수의 이름이 함수의 이름이 됨
function a(){} // 함수 선언
a(); // 함수 호출
function a(){
console.log('hello');
console.log('function');
}
a();
결과)
hello
function
function a(){}
//undefined
a();
//undefined
함수를 호출하면 항상 결과값이 나옴
결과값은 기본값으로 undefined가 나옴
이 값을 반환값이라 함
반환값을 직접 정할 수 있다.
function a(){
return 10;
}
//undefined
a();
//10
반환값도 값이므로 다른 식이나 문에 넣어 사용 가능
function a(){
return 10;
}
console.log(a());
함수의 반한값을 상수나 변수에 대입 가능
function a(){
return 10;
}
const b = a();
console.log(b);
return 문의 또 다른 기능 : 함수의 실행을 중지
function a(){
console.log('hello');
return;
console.log('return');
}
a();
결과 )
hello
인수 : 함수 호출 시 넣는 값
매개 변수 : 함수 선언 시 사용한 변수
함수는 여러개의 인수와 매개변수를 가짐
매개 변수와 인수의 개수가 일치하지 않아도 됨
function 함수명(매개변수1, 매개변수2,매개변수3){
실행문장;
return 반환값;
}
result = 함수명(인자1,인자2,인자3);
생각해보기!!
function add(){
let sum = 1;
return sum;
}
function add(x){
let sum = x + 1;
return sum;
}
function add(x,y){
let sum = x + y;
return sum;
}
function add(x,y,z){
let sum = x + y + z;
return sum;
}
let r0 = add();
let r1 = add(1);
let r2 = add(2,3);
let r3 = add(4,5,6);
let r4 = add(7,8,9,10);
console.log(r0);
console.log(r1);
console.log(r2);
console.log(r3);
console.log(r4);
결과 )
NaN
NaN
NaN
15
24
function minus1(x,y){
const a =100;
return (x-y)*a;
}
console.log(minus1(5,3));
함수 바깥에 위치한 변수나 상수 사용 가능
const a = 100;
function minus2(x,y){
return (x-y) * a;
}
console.log(minus2(5,3));
자신의 매개변수나 내부 변수만 사용하는 함수를 순수 함수 라고 함