Object Referencing Questions Javascript
- Objects Javascript questions
Q11. What's the Output? Object Referencing
let c = { greeting: "Hey!" };
let d;
d = c;
c.greeting = "Hello";
console.log(d.greeting);
?
Answer
let c = { greeting: "Hey!" };
let d;
d = c; // object is refered
c.greeting = "Hello";
console.log(d.greeting); // Hello
- Objects are not copied they are referenced
Q12. What's the output? Object Referencing
console.log({ a: 1 } == { a: 1 });
console.log({ a: 1 } === { a: 1 });
?
Answer
console.log({ a: 1 } == { a: 1 }); // false
console.log({ a: 1 } === { a: 1 }); // false
- Objects are only equal when they are referencing the same object
- As both objects are declared separately they are not the same object & therefore not equal
Q13. What's the output? Object Referencing
let person = { name: "Lydia" };
const members = [person];
person = null;
console.log(members);
person.name = null;
console.log(members);
?
Answer
let person = { name: "Lydia" };
const members = [person];
person = null;
console.log(members); // [ { name: "Lydia" } ]
person.name = null;
console.log(members); // [ { name: null } ]
Q14. What's the output? Object Referencing
const value = { number: 10 };
const multiply = (x = { ...value }) => {
console.log((x.number *= 2));
};
multiply();
multiply();
multiply(value);
multiply(value);
?
Answer
const value = { number: 10 };
const multiply = (x = { ...value }) => {
console.log((x.number *= 2));
};
multiply(); // 20
multiply(); // 20
multiply(value); // 20
multiply(value); // 40