Ellatronic
Design Portfolio

Blog

JavaScript: Understanding the Weird Parts (Part 6)

By Value vs. By Reference

  • Variables by value versus by reference.
  • by value - passing, referencing, or setting equal one value to another by copying the value
    • Two variables become the same by copying the value into two separate spots in memory.
  • by reference - two variables have the same value because they reference the same spot in memory
  • To summarize, by value means two variables pointing to two copies in different memory spots. By reference means two variables pointing to the same value in the same memory spot.
  • All objects interact by reference when setting them equal to each other or passing them to a function.
//by value (primitives)
var a = 3;
var b;
b = a;
  • b will be 3, a will be 3 but they are copies of each other sitting in different memory spots.
a = 2;
console.log(a); //a -> 2
console.log(b); //b -> 3
  • changing a does not affect b since they are in different memory spots.
//by reference (all objects, including functions)
var c = { greeting: 'hi'};
var d;
d = c;
  • Since these are objects, JavaScript points d to the same address as c.
c.greeting = 'hello'; //mutate
  • mutate - to change something
  • immuatable - cannot be changed
console.log(c); //-> {greeting: "hello"}
console.log(d); //-> {greeting: "hello"}

//by reference (even as parameters)
function changeGreeting(obj) {
    obj.greeting = 'Hola'; //mutate
}

changeGreeting(d);
console.log(c); //-> {greeting: "Hola"}
console.log(d); //-> {greeting: "Hola"}

//equals operator sets up new memory space (new address)
c = {greeting: 'howdy'};
console.log(c); //-> {greeting: "howdy"}
console.log(d); //-> {greeting: "Hola"}

All primitive types are by value and all objects are by reference.