Skip to content

Instantly share code, notes, and snippets.

@vxhviet
Last active June 28, 2023 12:39
Show Gist options
  • Save vxhviet/e95c4bffa6ed01e11e5f6b0356669e5c to your computer and use it in GitHub Desktop.
Save vxhviet/e95c4bffa6ed01e11e5f6b0356669e5c to your computer and use it in GitHub Desktop.

[JavaScript] - How Passing Arguments Works: Value vs Reference

SOURCE, SOURCE

JavaScript does not have pass by reference. The object passing might looks like passing by reference but it is still passing by value. The value here is the memory address in the stack that points to the object in the heap.

Again, JavaScript is a pure pass by value language. It's just that the values being passed around are references when not dealing with primitives

const flight = 'LH234';
const jonas = {
  name: 'Jonas Schmedtmann',
  passport: 24739479284,
};

const checkIn = function (flightNum, passenger) {
  flightNum = 'LH999';
  passenger.name = 'Mr. ' + passenger.name;

  if (passenger.passport === 24739479284) {
    alert('Checked in');
  } else {
    alert('Wrong passport!');
  }
};

checkIn(flight, jonas);
// flight is a string (primitive), so when passing it to a function it will create a new value (flightNum).
// Updating this value doesn't update the original value (pass by value).
console.log(flight);

// jonas is an object, so when passing it to a function, the reference in the stack is shared while the actual
// object values in the heap remains the same. Thus jonas is unexpectedly mutated too.
console.log(jonas);

const newPassport = function (person) {
  person.passport = Math.trunc(Math.random() * 100000000000);
};

newPassport(jonas); // jonas has been mutated
checkIn(flight, jonas); // thus it will show Wrong passport now
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment