Object references and copying Flashcards
let user = { name: ‘John’ };
let admin = user;
admin.name = ‘Pete’;
alert(user.name);
// returns and why?
// ‘Pete’, changes are seen from the “user” reference
let a = {};
let b = a;
alert( a == b ); // returns?
true, both variables reference the same object
let a = {};
let b = a;
alert( a === b );
// true
let a = {};
let b = {};
alert( a == b ); // returns and why?
false
And here two independent objects are not equal, even though they look alike (both are empty):
const user = {
name: “John”
};
user.name = “Pete”;
alert(user.name); //
returns and why
Pete
An important side effect of storing objects as references is that an object declared as const can be modified.
let user = {
name: “John”,
age: 30
};
let clone = {};
// copy all user properties into it for in loop
for (let key in user) {
clone[key] = user[key];
}
let user = { name: “John” };
Object.assign(user, { name: “Pete” });
alert(user.name); // returns and why?
now user = { name: “Pete” }
If the copied property name already exists, it gets overwritten
let user = {
name: “John”,
age: 30
};
let clone = // assign user to clone
alert(clone.name); // John
alert(clone.age); // 30
Object.assign({}, user);
let user = {
name: “John”,
sizes: {
height: 182,
width: 50
}
};
alert( ); // 182
how to access 182?
user.sizes.height
let user = {
name: “John”,
sizes: {
height: 182,
width: 50
}
};
let clone = Object.assign({}, user);
alert( user.sizes === clone.sizes ); // returns and why?
// true, same object
let user = {
name: “John”,
sizes: {
height: 182,
width: 50
}
};
user.sizes.width = 60; // returns
user.sizes.width = 60; // change a property from one place
let user = {
name: “John”,
sizes: {
height: 182,
width: 50
}
};
let clone = Object.assign({}, user);
alert( user.sizes === clone.sizes ); //
True
The call _______clones the object with all nested properties.
structuredClone(object)
let user = {
name: “John”,
sizes: {
height: 182,
width: 50
}
};
let clone = structuredClone(user);
alert( user.sizes === clone.sizes );
// false, different objects
let user = {};
user.me = user;
let clone = structuredClone(user);
alert(clone.me === clone); //
returns and why?
true
// let’s create a circular reference:
// user.me references the user itself