Search code examples
javascriptpass-by-value

Pass by value and memory consumption in JavaScript


Let's say I got this code:

function MinMax(list) {
  const min = Math.min(...list);
  const max = Math.max(...list);

  return {
    min,
    max,
    list,
  };
}

const massiveList = [
  1,
  // supposedly a gazillion
  // integer values
  10000000,
];

const minMax = MinMax(massiveList);

const minMaxList = minMax.list;

console.log('min              ', minMax.min);
console.log('max              ', minMax.max);
console.log('minMaxList length', minMaxList.length);

Here's my question: since arguments are passed by value in JavaScript, does that mean, that after that point in code, where minMax.list is assigned to minMaxList, three copies of the original massiveList exist in heap memory?


Solution

  • You can try the below demo with reference value

    const massiveList = [
      1,
      // supposedly a gazillion
      // integer values
      10000000,
    ];
    
    const testReference = (list) => {
       console.log(list === massiveList) //true
    }
    
    testReference(massiveList)

    In your case, list and massiveList are the same reference which means any modification on list will be applied on massiveList as well.

    ...list means you've cloned the original list to another list that will be allocated newly in the memory.

    The below demo is to show reference values get changed for the new list, so that's why the result is false

    const massiveList = [
      1,
      // supposedly a gazillion
      // integer values
      10000000,
    ];
    
    const testReference = (list) => {
      const newList = [...list]
      console.log(list === newList) //false
    }
    
    testReference(massiveList)