Call by Value vs. Call by Reference

Lami·2022년 11월 20일

JavaScript

목록 보기
2/2
post-thumbnail

call by ~ : 인자가 매개변수로 전달될 때 전달하는 방식

  • 인자(Argument) - 함수 호출 시에 전달되는 값 / 매개변수(Parameter) - 전달된 인자를 받아들이는 변수

JavaScript는 기본적으로 항상 call by value 지만 참조형 type의 data(객체, 배열 등)일 경우 call by reference

call by value : 복사된 값을 인자로 넘겨서 파라미터로 전달(파라미터로 넘어온 값들을 변경해도 원시값이 변하지 않음 - 을 사용)

call by reference : 실제 데이터가 존재하는 주소를 가리키는 주소값을 인자로 넘겨서 매개변수로 전달(파라미터로 넘어온 값을 변경하면 원시값이 변함 - 참조값 사용)

call by reference

enter image description here

// 객체
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]

call by value

enter image description here

// 숫자
const num = 12;

function changeNum(a) {
  a = 30;
  console.log(a);
}

changeNum(num); // 30
console.log(num); // 12

call by reference + call by value

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]
profile
삶이 온통 사람의 길이니 많은 경험을 해보고 싶은 프론트엔드 개발자 지망생입니다.

0개의 댓글