Object
Description
The Object class is the foundation of JavaScript’s object-oriented system. Every object in JavaScript inherits properties and methods from Object.prototype, making it the most fundamental constructor in the language. Objects in JavaScript are collections of key-value pairs, where keys are strings (or Symbols) and values can be any data type including other objects, functions, or primitive values.
The Object class provides static methods for working with objects directly, rather than through object instances. These methods allow you to create objects, copy properties, define property descriptors, and inspect object structures. Understanding Object is essential because it underlies nearly everything in JavaScript—from plain objects and arrays to function prototypes and class instances.
Methods
Object.create()
Creates a new object with a specified prototype and optional properties.
const person = {
isHuman: false,
printIntroduction: function() {
console.log(`My name is ${this.name}. Am I human? ${this.isHuman}`);
}
};
const me = Object.create(person);
me.name = 'Matthew';
me.isHuman = true;
me.printIntroduction();
// Output: "My name is Matthew. Am I human? true"
Object.assign()
Copies enumerable own properties from one or more source objects to a target object.
const target = { a: 1, b: 2 };
const source = { b: 4, c: 5 };
const returnedTarget = Object.assign(target, source);
console.log(target);
// Expected output: Object { a: 1, b: 4, c: 5 }
console.log(returnedTarget);
// Expected output: Object { a: 1, b: 4, c: 5 }
Object.keys()
Returns an array of a given object’s own enumerable property names.
const object1 = {
a: 'somestring',
b: 42,
c: false
};
console.log(Object.keys(object1));
// Expected output: Array ["a", "b", "c"]
Object.freeze()
Freezes an object, preventing modifications to its properties.
const obj = {
prop: 42
};
Object.freeze(obj);
obj.prop = 33;
// Throws an error in strict mode
console.log(obj.prop);
// Expected output: 42
Object.entries()
Returns an array of key-value pairs for each enumerable own property.
const object1 = {
a: 'somestring',
b: 42
};
for (const [key, value] of Object.entries(object1)) {
console.log(`${key}: ${value}`);
}
// Output: "a: somestring"
// Output: "b: 42"
See Also
- Map — Key-value collections with better iteration support
- Object.keys() — Get an array of an object’s own enumerable property names