Day14 of #100DaysOfCode
Hii folks 🙌
Today I have completed the 14th video of JavaScript30!
Project 14: Object and Arrays — Reference VS Copy
Source: https://javascript30.com
Learnings:
- strings, numbers, and booleans
Javascript will make copies of these types, so changing the values like below is okay.
let age = 100;
let age2 = age;
age = 200;
In this case, the age2
variable will keep its originally assigned value of 100
.
- array
When dealing with arrays, you need to be aware of the concept of references.
const players = ['Kushagra', 'Sarah', 'Ryan', 'Poppy'];
const team = players;
Here, modifying the team
array's values will actually modify the players
array, for example…
team[3] = 'Lux';
console.log(players[3]); // 'Lux'
To leave the original array intact, you must make copies of it. There are multiple ways of doing this, some are shown below.
const team2 = players.slice();
const team3 = [].concat(players);
const team4 = [...players];
const team5 = Array.from(players);
- objects
The same principle of referencing (from arrays) applies here. To copy an object to another variable, the following code would work
const person = {
name: 'Kushagra Kesav',
age: 20
};
const cap2 = Object.assign({}, person, { age: 99 });
The Object.assign()
method takes in the following parameters:
target
- In this case, a blank object{}
sources
- Object(s) to add
The additional argument.
{age: 99}
- This will modify the existing age variable in person
Things to note — this is only 1 level deep — both for Arrays and Objects, which means it will update the embedded object that is `social.twitter` and `social. medium`, even if you update the copy of the object!!
const details = {
name: 'Kushagra',
age: 100,
social: {
twitter: '@im_Kushagra',
medium: '@imKushagra'
}
};console.log(details);const dev = Object.assign({}, details);
To, skip that functionality or cheat the way out you can use the following line of code to create the copy of the object! (not recommended)
const dev2 = JSON.parse(JSON.stringify(details));
Today I learned (T-I-L):
- Objects & Arrays in JS
- String, Number & Booleans in JS
- Difference between JS referencing and copying
- The embedded object will get updated even after copying the object ✨
That is all for Day14 ✅
Thanks for reading, See you tomorrow!