
call by ~ : 인자가 매개변수로 전달될 때 전달하는 방식
JavaScript는 기본적으로 항상 call by value 지만 참조형 type의 data(객체, 배열 등)일 경우 call by reference
call by value : 복사된 값을 인자로 넘겨서 파라미터로 전달(파라미터로 넘어온 값들을 변경해도 원시값이 변하지 않음 - 값을 사용)
call by reference : 실제 데이터가 존재하는 주소를 가리키는 주소값을 인자로 넘겨서 매개변수로 전달(파라미터로 넘어온 값을 변경하면 원시값이 변함 - 참조값 사용)

// 객체
const person = {
name: "Tom",
age: 24,
};
function changeAge(a) {
a.name = "Lee";
console.log(a);
}
changeAge(person); // { name: 'Lee', age: 24 }
console.log(person); // { name: 'Lee', age: 24 }
// 배열
const arr = [10,20,40];
function changeArr(a) {
a.push(7);
console.log(a);
}
changeArr(arr); // [10, 20, 40, 7]
console.log(arr); // [10, 20, 40, 7]

// 숫자
const num = 12;
function changeNum(a) {
a = 30;
console.log(a);
}
changeNum(num); // 30
console.log(num); // 12
let arr = [1, 2, 3, 456, 54, 323, 456];
arr.forEach((item, index) => {
console.log(arr[index]); // 1, 2, 3, 456, 54, 323, 456
console.log(item); // 1, 2, 3, 456, 54, 323, 456
if (index % 2 === 0) {
arr[index] = 0; // call by reference => 배열이 저장된 메모리 주소 참조해서 값 변경
} else {
item = -1; // call by value => 값을 복사해서 변경하려 했으나 원시배열은 변하지 않음
}
});
arr; // [0, 2, 0, 456, 0, 323, 0]