Objects are a reference data type. I.e., variables and constants do not store the objects themselves (their data), but a reference to them. So, it might feel like constants in JavaScript can be changed, but this isn't the case. The main thing to understand is that when it comes to objects, constants are linked with the reference, not the data:
const company = {};
// It's possible to change the object
company.name = 'Hexlet';
// You can't replace the reference
company = {}; // Boom!
let object = {};
// But you can do this
object = {};
That they are reference data also affects comparison. Objects that have the same structure aren't equal to each other. The only time they can be equal is if they are the same object:
const company = { name: 'Hexlet' };
company === { name: 'Hexlet' }; // false
const copyOfCompany = company; // passing a reference
// It's the same thing
copyOfCompany === company; // true
// By changing one thing, we change another
company.createdAt = 2012;
console.log(copyOfCompany); // { name: 'Hexlet', createdAt: 2012 }
Every object declaration (including an empty one), creates a new object. Therefore, even two empty objects are never equal to each other:
{} === {}; // false
The referential nature of objects affects how they work with functions most of all. Any object passed to a function gets there via a reference. Changing such an object inside a function changes it from the outside as well:
const changeObj = (o) => {
o.key = 'value';
};
const obj = {};
changeObj(obj);
console.log(obj); // { key: 'value' };
Are there any more questions? Ask them in the Discussion section.
The Hexlet support team or other students will answer you.
For full access to the course you need a professional subscription.
A professional subscription will give you full access to all Hexlet courses, projects and lifetime access to the theory of lessons learned. You can cancel your subscription at any time.