Skip to content

Instantly share code, notes, and snippets.

@kkarrwrites
Last active September 7, 2023 19:32
Show Gist options
  • Save kkarrwrites/1be289676b283193cc119740c39d3131 to your computer and use it in GitHub Desktop.
Save kkarrwrites/1be289676b283193cc119740c39d3131 to your computer and use it in GitHub Desktop.

Pass by Reference vs. Pass by Value

These are my notes taken while studying Web Dev Simplified's video tutorial on passing by reference versus passing by value in JavaScript.

Pass by Value

When you set a variable to a primitive value or primitive data type, you are using pass by value, which means that the value is set to what the variable actually equals.

let a = 10; // 10
let c = a; // 10
c = c + 1; // 11

In this example, "c" is set to the value of 10 and "a" is set to the value of 10, but they are two different values. So when one is added to "c," it updates "c" to 11, but "a" remains 10.

Pass by Reference

When you set a variable to an array or object, you are using pass by reference, which means that the value is set to a reference to that array or object.

let d = [1, 2]; // Memory address that has the value of [1, 2]
let e = d; // The same memory address as d that has the value of [1, 2]

Both "d" and "e" will point to the same memory address in your code. This means that if you update the value of "d," the value of "e" will aslo be updated.

If, however, you set "e" to a new array, it will create a new address in memory that has the value of that new array.

e = [3, 4] // New memory address that has the value of [3, 4]

Resources

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment