Javascript object | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Javascript object

let person = { name: 'Jack', age: 18, sex: 'male' }; let student = { name: 'Bob', age: 20, xp: '2' }; let newStudent = Object.assign({}, person, student); console.log(newStudent.name); // Bob console.log(newStudent.age); // 20 console.log(newStudent.sex); // male console.log(newStudent.xp); // 2 while console logging I am getting the result I have shown after //. How would I came up to know that newStudent.name will print Bob why not Jack . and why newStudent.age will print 20 why noyt18 ?

21st Sep 2019, 10:47 AM
Abdur Rehman Siddiqui
Abdur Rehman Siddiqui - avatar
4 Answers
+ 4
The syntax of Object.assign() looks like this Object.assign(target, ...sources) and it returns the target object. So, in your code, the target object is {} and the sources include person object and student object. It will clone a person object and student object to the target object. The reason why nameStudent.name show Bob because the properties are overwritten by other objects that have the same properties later in the same order of parameters.
21st Sep 2019, 11:34 AM
Phurinat Puekkham
Phurinat Puekkham - avatar
+ 1
First person is assigned to an empty object then student is assigned to this new object. When an object is assigned it will overwrite all previous members with its own values. Therefore student overwrites persons name and age attributes. If you change the order it will be the other way around.
21st Sep 2019, 11:36 AM
Aaron Eberhardt
Aaron Eberhardt - avatar
+ 1
Thanks guys for your help
21st Sep 2019, 11:38 AM
Abdur Rehman Siddiqui
Abdur Rehman Siddiqui - avatar
0
Great explanation by Phurinat Puekkham
19th Nov 2019, 9:54 AM
subyyal
subyyal - avatar