JavaScript-30-Day-14
Tags: javascript, webdev, github, programming
Published: 2021-06-14 16:45:48

## <center>JavaScript References VS Copying</center>

## [demo](https://cenacrharsh.github.io/JS-30-DAY-14/)

![ss](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/uaz3vgb0yt0a6jqbv0i3.png)

On Day-14 of JavaScript-30 we discussed a very important concept of JavaScript or any programming language for that matter, the difference between and a reference and copy.

We'll start with:

## Strings, Numbers and Booleans

let's say we have a variable `age=100`, now we create another variable `age2=age`, now if we `console.log()` them we'll see they have the same values in them.

Now what happens if we do `age=200`, now if we try `console.log()` them we'll see value of `age` is changed but but the value of `age2` is unchanged.

I have provided the output in comments.

```javascript
let age = 100;
      let age2 = age;
      console.log(age, age2); // 100 100
      age = 200;
      console.log(age, age2); // 200 100
```

This tells us when we created `age2` using the `age` then a separate copy was made for `age2`, hence when `age` was changed we do not see the effects of those changes on `age2`.

The same happens with Strings:

```javascript
let name = "harsh";
      let name2 = name;
      console.log(name, name2); // harsh harsh
      name = "kumar";
      console.log(name, name2); // kumar harsh
```

So in the case of Strings, Numbers and Booleans, while creating new copies of them a separate copy is created and we can make changes in one without affecting the other one.

## Arrays

Let's say we have an array

```javascript
const players = ["Wes", "Sarah", "Ryan", "Poppy"];
```

and we want to make a copy of it.

 You might think we can just do something like this:

```javascript
const team = players;
```

We print them and see:

```javascript
console.log(players, team);
// ["Wes", "Sarah", "Ryan", "Poppy"]
// ["Wes", "Sarah", "Ryan", "Poppy"]
```

We can see that both arrays contain same elements.

However what happens when we update that array?

```javascipt
team[3] = "Lux";
```

Now here is the problem! When we print them we see:

```javascript
console.log(players, team);
// ["Wes", "Sarah", "Ryan", "Lux"]
// ["Wes", "Sarah", "Ryan", "Lux"]
```

We see that we have edited the original array too!

**Why?** It's because `team` isn't another array, it is just a reference to the original Array.

So we see when we try to copy arrays we get what is an array reference, not an array copy.In reality they both point to the same array!

So if we try to make changes in one of the arrays that change will be reflected in the other one.

So, how do we fix this? We take a **copy** instead!

And how do we do that? Well there are multiple ways to do that and we'll see a bunch of them.

## `slice`

```javascript
      const team2 = players.slice();
```
If you pass nothing to `splice` it will simply return a copy of the original array.

## `concat`

```javascript
const team3 = [].concat(players);
```

What we are doing here is take an empty array and concatenate the old one with it thus getting the same elements as the original array.

## `Array.from`

```javascript
const team5 = Array.from(players);
```

## ES6 `spread`

```javascript
const teams4 = [...players];
```

This is the latest and the easiest method of creating copies of array.

`spread` takes every item out of a iterable and puts it into the container, here an array.

You can read more about spread operator on [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax)

    
Using any of the above methods we can create copies of arrays and now when we update it, the original one isn't changed.

## Objects

The same thing goes for objects, let's say we have a person object

```javascript
      const person = {
        name: "Wes Bos",
        age: 80,
      };
```
 
and think we make a copy, but instead we get a reference and making changes would affect both.

```javascript
const captain = person; //captian is just a reference
captain.number = 100; // changes person as well
```

Again what we do is we take a copy instead using `Object.assign()`

```javascipt
const cap2 = Object.assign({}, person, { number: 99 });
```

`Object.assign()` takes 3 arguments, first one is an empty object, second we pass it the object we wish to copy all the properties from and an optional third argument where we pass our own properties we would like to add to the object or existing properties whose value we would like to update, and this won't affect the original object.

![1](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6o98c305u89gkzavovbo.png)

We can also use the `spread` operator like arrays.

```javascript
const cap3 = { ...person };
```

>Things to note - this is only 1 level deep - both for Arrays and Objects. lodash has a cloneDeep method, but you should think twice before using it.

So what do I mean by 1 level deep, we saw when we changed the `name` property the original object was unchanged, but what if try to change `social` property which itself is an object.

Take a loot at this:

```javascript
const harsh = {
        name: "harsh",
        age: 20,
        social: {
          twitter: "@harsh",
          fb: "harsh",
        },
      };

const newObject = Object.assign({}, harsh);
```

![2](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2zsxpbu1xqtj40hujzi7.png)

So we see that a change in the `fb` property inside `social` affected the original object as well. And this is why we say that all this techniques of copying are shallow copy as they work only up to one level, beyond that we need a deep copy which is a bit complicated.

We can use a shortcut though but it isn't recommended as behaviour can be unexpected.

What we can do is use:

```javascript
const newObject2 = JSON.parse(JSON.stringify(harsh));
```

and you can see the results:

![3](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mwdw3zbtb25xyaowlia0.png)

We can see that the change is the `social` property will not affect the original object now.

**Why?** you may think

Because if we pass an object to `JSON.stringify` like `JSON.stringify(harsh)` then it simply converts it into a string, it is no longer an object, but then we immediately `JSON.parse` it  like `JSON.parse(JSON.stringify(harsh))` which turns it back into an Object and thus we get a full copy of the original object without any issue of references.

and with this our project for the day was completed.

GitHub repo:
{% github cenacrharsh/JS-30-DAY-14 no-readme %}

###Blog on Day-13 of javascript30
{% link https://dev.to/cenacr007_harsh/javascript-30-day-13-337i %}

###Blog on Day-12 of javascript30
{% link https://dev.to/cenacr007_harsh/javascript-30-day-12-2k45 %}

###Blog on Day-11 of javascript30
{% link https://dev.to/cenacr007_harsh/javascript-30-day-11-1icc %}

[Follow me on Twitter](https://twitter.com/cenacr007_harsh)
[Follow me on Linkedin](https://www.linkedin.com/in/kumarharsh22/)

**DEV Profile**

{% user cenacr007_harsh %}

You can also do the challenge at [javascript30](https://javascript30.com/)

Thanks @wesbos , [WesBos](https://github.com/wesbos) to share this with us! 😊💖

**Please comment and let me know your views**
##Thank You!