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' };
The Hexlet support team or other students will answer you.
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.
Programming courses for beginners and experienced developers. Start training for free
Our graduates work in companies:
Sign up or sign in
Ask questions if you want to discuss a theory or an exercise. Hexlet Support Team and experienced community members can help find answers and solve a problem.