As with before, you can also add and remove properties using this syntax - it's just another way to write a property access, and in principle works the same as using a dot.
Providing the property has a valid name, you can access it both ways: with a dot or with a string.
let myObject = {
myProperty: 5
};
// Read with dot property
console.log(myObject.myProperty); // 5
// Read with string property
console.log(myObject["myProperty"]); // 5
One reason to use string properties is you can use a string variable, or in fact any expression returning a string, to access a property name. This is not possible when using a dot to access properties, since you can only use a fixed name.
let myObject = {
myProperty: 5
};
// Access a property via a string variable
let propName = "myProperty";
console.log(myObject[propName]); // 5
This can be useful to change which properties are accessed depending on conditions. For example you could have an 'if' statement that changes the property name to be accessed.
Testing for properties
We previously saw how accessing a missing property returns undefined
. However it's also possible to store undefined
on a property. This means you can't use undefined
to tell whether a property exists on an object or not, as you can't tell apart "missing" from "exists but has value undefined".
let myObject = {
myProperty: undefined
};
// Reading a missing property returns undefined
console.log(myObject.otherProperty); // undefined
// But reading myProperty also returns undefined
console.log(myObject.myProperty); // undefined
So to tell if a property really exists on an object, JavaScript provides the in
operator. Due to the syntax used, the property name must be a string though. So using "propertyName" in myObject
will return a boolean with true
if the property name exists on the given object, or false
if it does not exist. Remember that since string and normal names are interchangeable, this still works for normal properties too.
let myObject = {
myProperty: undefined
};
console.log("otherProperty" in myObject); // false
console.log("myProperty" in myObject); // true