Objects are one of the most powerful features in JavaScript. You’ve already seen basic object usage — here we’ll dive deeper into how objects work and how to manipulate them.
1. Creating Objects
There are different ways to create objects in JavaScript:
Theperson
object is created using an object literal. TheStudent
object is created using a constructor function. A function that creates an object like this is called a constructor function.
2. UsingObject.keys()
To list all the property names of an object:
3. Looping Through Properties
Usefor...in
to loop through all enumerable properties:
4. Understanding Property Descriptors
Every property in an object has a property descriptor that describes its behavior:
- value: The actual value of the property.
- writable: Can the value be changed?
- enumerable: Will it show in loops like
for...in
? - configurable: Can the descriptor itself be changed?
5. Modifying Descriptors withObject.defineProperty()
'use strict';
function Student() { this.name = "Steve"; this.gender = "Male"; }
const student1 = new Student();
Object.defineProperty(student1, 'name', { writable: false });
try { student1.name = "James"; // Throws an error in strict mode console.log(student1.name); } catch (e) { console.log(e.message); }
Since we madename
non-writable, trying to change its value throws an error in strict mode.
6. Hiding a Property (Non-enumerable)
After settingenumerable
tofalse
, thename
property will no longer show in loops orObject.keys()
.
7. Making a Property Non-configurable
Once a property is non-configurable, you can’t change its descriptor again (e.g., writable, enumerable).
Summary
- Objects store data as key-value pairs.
- Use constructor functions to create multiple similar objects.
Object.keys()
andfor...in
can list object properties.- Each property has a descriptor with settings like writable and enumerable.
- Use
Object.defineProperty()
to control how properties behave.