
함수 : 프로그램을 구성하는 주요 구성 요소이다.
함수를 이용하면 중복없이 유사한 동작 코드를 여러 번 호출할 수 있다
ex) 내장함수 : alert, prompt, confirm
데이터를 함수 안에 전달되는 변수, 함수에서 정의되어 사용되는 변수
function showMessage(from, text) {
// 인자: from, text
console.log(from + ': ' + text);
}
showMessage('홍길동', 'Hello!'); // 홍길동: Hello!
showMessage('홍길동', "안녕?"); // 홍길동: 안녕?
✔️인자(parameter) vs 인수(argument, 전달인자)
인자 : 함수 정의할 때 사용되는 변수
인수 : 실제 함수를 호출할 때 넘기는 변수값function plus (**num1, num2**) { return num1 + num2; } // num1, num2는 parameter이다. plus(10, 20); // 10, 20은 argument이다.
❗️매개변수에 인수를 전달하지 않으면 undefined가 된다
function showMessage(from, text) { // 인자: from, text console.log(from + ': ' + text); } showMessage('홍길동'); // 홍길동: undefined
❓그럼 undefined 표시 안 하고 싶으면?
매개변수 text가 값 전달받지 않아도 직접적으로 값을 넣어줄 수 있다.
이때 undefined와 엄격일치해도 표현된다function showMessage(from, text="표시안함") { // 인자: from, text console.log(from + ': ' + text); } showMessage('홍길동'); // 홍길동: 표시안함 showMessage('홍길동',undefined); // 홍길동: 표시안함
function showMessage(from, text=anotherFunction()) { // 인자: from, text console.log(from + ': ' + text); }text에 값이 전달되면 anotherFunction()은 호출되지 않는다
text에 값이 없는 경우에만 showMessage() 호출 → anotherFunction() 호출
✔️인자 넘기는 방식
원시타입(변경 불가능한 값)
- 원시 타입 데이터는 변수에 할당될 때, 메모리 상에 고정된 크기 저장, 해당 변수가 원시 데이터 값을 보관한다
- Boolean, number, string, null, undefined
Pass By Value 형식으로 넘겨준다- 데이터 신뢰성 보장
- 값이 동일하지, 다른 메모리 공간에 저장된 별개 값이다.
let score = 80; let copy = score; console.log(score, copy) // 80 80 console.log(score === copy) // true객체타입
- 참조 타입 데이터는 크기가 정해져 있지 않다.
- 값이 직접 해당 변수에 저장되지 않기에, 변수에 데이터 참조 저장이 된다.
- 저장된 힙 메모리 주소값을 저장하는 것
- Object, Array, Function
Pass By Reference 형식으로 넘겨준다- 메모리 주소는 다르지만 동일한 참조 값을 가진다
= 2개의 식별자가 하나의 객체 보유
= 객체값이 달라지면 영향을 받는다
function showMessage(parameter1, parameter2...) {
console.log( '안녕하세요' );
}
showMessage(); // 함수호출
함수 내에서 선언한 변수
function showMessage() {
let message = "안녕하세요!"; // 지역 변수
console.log( message );
}
showMessage(); // 안녕하세요!
console.log( message );
// ReferenceError: message is not defined
// (message는 함수 내 지역 변수이기 때문에 에러가 발생한다)
함수 내부에서 함수 외부 변수에 접근할 수 있다
let userName = 'John';
function showMessage() {
let message = 'Hello, ' + userName;
console.log(message);
}
showMessage(); // Hello, John