JavaScript 30 — Day 14 — JavaScript References VS Copying

Steven Chen
2 min readDec 16, 2021

--

I fell a few days behind in this challenge but have no fear, cramming out a few in one day was never off the table, so here we go.

This exercise was a quick review of how different data types are passed value.

The long and short of it (or as the kids say these days the TLDR) is that in JavaScript primitive data types (numbers, strings, booleans) are stored and passed by value whereas Objects are stored and passed by reference.

Since this is a real short one and me writing here won’t give you any info than a lot of great resources have done before.

So here are a couple I liked the explanation of:

Arrays:

I like this one because it reviews a lot of the Array methods that are oh so useful.

Objects:

Some things to note:

  • These are shallow (one level) copies or clones, meaning that if there are nested Arrays or Objects, these methods don’t work out so well.
  • For deeper clones (multiple levels) you can use the method .cloneDeep() but you will need to import Lodash, which may be more than is required.
  • While not particularly elegant, a pretty clever way to do a deep clone is to do a JSON.stringify() on the Object, then a JSON.parse() to make a clone. I kind of like this
  • This challenge is a few years old so the Object spread ({…}) that Wes says is upcoming, does indeed exist as of ECMA Script 2018.

--

--