Before going to details about copy by value and copy by reference first, we need to know about Primitive datatype and non-primitive data type
What is a Primitive data type?
Primitive data types are :
-Number -Boolean -Undefined -String -Null
The non-primitive data types are:
Object Array
copy by Value:- When we pass Primitive data types we actually share value to the other data types. Let's see an example
let a=10;
let b=a;
b=20;
console.log(a) // 10
console.log(b) // 20
In the above example, we actually pass the value of a so change in b will not reflect in a.Same concept apply to all other primitive data types as well.Let's see an another example of copy by value
let str1 = "car";
let str2 = str1;
str2 = "truck";
console.log(str1) // car
console.log(str2) // truck
copy by reference:- In non-primitive data type we pass reference means address of a variable .Let's see an example
let person = {
name: 'John',
age: 25,
};
let newPerson=person;
newPerson.age=30;
console.log(person) // {name: 'John', age: 30}
here person.age value also changed because we pass address of person so newperson can access all the values of person and can manipulate also which will reflect on person also