Let's talk about JavaScript reference types
The very nice folks who run FreeCodeCampOKC invited me to give a presentation over Intro to JavaScript. I’m so glad they did, and I had a blast! I love talking about, and teaching about, JavaScript. JavaScript is a great programming language to begin with because it’s so accessible to run – all you need is a browser!
I got a question at the end about reference types in JavaScript, and that question got me thinking.
Most types in JavaScript are value types. This means that each variable has it’s own value. Copying variables with value types is a breeze. It just looks like this:
var a = "Hello World";
var b = a + "!";
console.log(a); // Hello World
console.log(b); // Hello World!
JavaScript objects on the other hand are not value types – they are reference types. A reference type means that the variable (in our case, an object) points to a specific place in memory. How is this so different from a value type?
Reference types don’t copy the same way. Because they point to a place in memory when you copy an object (var objB = objA
) you end up with two variables pointing to the same place in memory. So changes to either variable will affect both variables.
Well, we know that is true for objects … but what about arrays?
In JavaScript, array is not actually a type, instead array is an object. So it turns out that you’ll have the same problem with arrays.
Check it out!
var objA = {
name: 'Rey',
age: '26',
occupation: 'Jedi'
};
var arrA = ['Anakin', 'Padme', 'Luke', 'Leia', 'Ben'];
function mutateObj(tmpObj) {
var tmp = tmpObj;
tmp.name = 'Finn';
return tmpObj;
}
function mutateArr(tmpArr) {
var tmp = tmpArr;
tmp[0] = 'Obi-Wan';
}
var objB = mutateObj(objA); // we now have two matching objects
var arrB = mutateArr(arrA); // we now have two matching arrays
You can check out my demo here.
In my next post, I’ll show you how you can copy arrays and objects into a new variable. This way, you won’t have issues with changes on your new object or array affecting your old one.