- An empty object can be created using one of two syntax:
let user = new Object(); // "object constructor" syntax
let user = {}; // "object literal" syntax
let user = {
name: "John",
"Full Name": "John Smith",
// The last property in the list may end with a comma.
// That is called a “trailing” or “hanging” comma.
"age": 30,
};
user.isAdmin = true; // Extend object properties.
// To remove a property, we can use delete operator:
delete user.age;
// For multiword properties, the dot access doesn’t work.
user["Full Name"] = "New Value";
delete user["Full Name"];
let key = "age";
console.log(user[key]);
- We can use square brackets in an object literal.
- That’s called computed properties.
let fruit = "apple";
let bag = {
[fruit]: 5, // the name of the property is taken from the variable fruit
[fruit + 'Computers']: 5, // bag.appleComputers = 5
};
console.log(bag.apple); // 5
let bag = {};
bag[fruit] = 5; // Take property name from the fruit variable.
- Reserved words are allowed as property names.
- Basically, any name is allowed, but there’s a special one: "
__proto__
" that gets special treatment for historical reasons.
- The use-case of making a property from a variable is so common, that there’s a special property value shorthand to make it shorter.
function makeUser(name, age) {
return {
name, // same as name: name
age, // same as age: age
};
}
Property Checking
- A notable objects feature is that it’s possible to access any property.
- There will be no error if the property doesn’t exist.
- Accessing a non-existing property just returns
undefined
.
- A special operator "
in
" allows to check for the existence of a property.
let myObject = {
"myKey": null
};
if ("myKey" in myObject) {
// Do something...
}
- Usually, the strict comparison "
=== undefined
" check works fine.
- When an object property exists, but stores undefined, it fails, but "
in
" works correctly.
let obj = {
test: undefined
};
console.log(obj.test); // It's undefined.
console.log("test" in obj); // true, the property does exist.
for…in
Loop
- It allows you to walk over all keys of an object, there exists a special form of the loop:
for..in
.
for (userKey in user) {
// Executes the body for each key among object properties
}
Comparison
- When it comes to comparison, the equality == and strict equality === operators for objects work exactly the same.
- Two objects are equal only if they are the same object.
- For comparisons like obj1 > obj2 or for a comparison against a primitive obj == 5, objects are converted to primitives.