Hello World,
Today I want to talk about how to define objects and their properties in Javascript. For me, it is a Back to the basics
post. Let's dive in.
//@ts-check
"use strict";
const person = {
name: "chety",
};
We basically create an object via object literal
above. When you define a property like that your property is basically writable, configurable, enumerable by default. What do these mean actually?
- Writable: Your property value can be changed via assignment if it is true.
- Configurable: Your property can be deleted from your object if it is true.
- Enumerable: Your property can be seen when the enumeration process takes place(via for, for ... of)
console.log(Object.keys(person)); // -> [ 'name' ]
Let's create another property via Object.defineProperty
.
Object.defineProperty(person, "secretProp", {
//normally below properties are false by default when creating a property via Object.defineProperty
writable: false, // -> You can't change property value via assignment
configurable: false, // -> You can't delete property from object
enumerable: false, // -> property will not be seen with enumuration process(for, for of ...)
//If we define get and set then we can not use value property directly
//value: 42,
// If we define writable property then we can not use get and set
// get(){
// return this["_secretProp"]
// },
// set(value){
// this["_secretProp"] = value
// }
});
If we want to see our person's keys Object.keys(person)
will only return the enumerable properties. If we want to see all the properties(enumerable/nonenumerable) we can use Object.getOwnPropertyNames(person)
console.log(Object.keys(person)); // -> [ 'name' ]
console.log(Object.getOwnPropertyNames(person)); // -> [ 'name', 'secretProp' ]
But what if we want to add a property whose key is a Symbol
? Let's try this.
const age = Symbol("age");
person[age] = 33;
So when we try to access our person
keys none of the above methods return this new age
property. To access all the keys(string, symbol ...etc) we can use Reflect.ownKeys(person)
console.log(Object.keys(person)); // -> [ 'name' ]
console.log(Object.getOwnPropertyNames(person)); // -> [ 'name', 'secretProp' ]
console.log(Reflect.ownKeys(person)); // -> [ 'name', 'secretProp' , Symbol(age)]
That's it for today guys. If you have any ideas, feedbacks ...etc please do not hesitate to share in the comments. Stay tuned bye-bye.