서비스를 만들다 보면 같거나 비슷한 동작이 생김 ( 팝업, 결제 등 )
자주, 여러곳에서 사용하면 하나로 만들어 재활용하여 중복되는 코드를 줄이고 유지보수를 편하게 하기 위해 함수를 만듦
브라우저가 내장하고 있는 함수 console, arlet, confirm 가 있음
// 함수 작성
function 함수이름(변수) {
// 명령들 ..
}
함수이름 (데이터);
// 인수 (데이터)와 변수(매개변수) 사용
// 매개변수 없는
function showError() {
alert('에러발생');
}
showError();
// 매개변수 있는
function sayHello(name) {
const msg = `Hello, ${name}`;
console.log(msg);
}
sayHello('Mike');
sayHello('Tom');
❗️ 매개변수가 여러개인 경우 쉽표로 구분 가능
지역변수 : 함수 내부에서만 접근가능
⭐️ 예시
let msg = "welcome"; // 전역변수
console.log(msg); // "welcome"
function sayHello(name) {
let msg = "Hello"; // 지역변수
console.log(msg + '' + name); // "HelloMike"
}
sayHello ('Mike');
console.log(msg); // "welcome"
-----------------------------------------------
let name = "Mike";
function sayHello(name) {
console.log(name) // undefined
}
sayHello();
sayHello('jane'); // "jane"
매개변수로 받은 값은 복사된 후 함수의 지역변수가 됨
전역변수가 많아지면 관리가 힘들어지기 때문에 함수에 특화된 지역변수를 쓰는 습관을 들이는게 좋음
// OR
function sayHello(name) {
let newName = name || 'friend';
let msg = `Hello, ${newName}`;
console.log(msg); // "Hello, friend"
}
sayHello();
sayHello('jane'); // "Hello, jane"
---------------------------------------
// default value
function sayHello(name = 'friend') {
let msg = `Hello, ${name}`;
console.log(msg); // "Hello, friend"
}
sayHello();
sayHello('jane'); // "Hello, jane"
❗️ 참고