What is an Object in JavaScript?
In JavaScript, an object is a standalone entity with properties and methods. Properties are key-value pairs that define the characteristics of the object, while methods are functions that perform operations on or with the object's data.
Objects are variables too. But objects can contain many values.
This code assigns many values (Fiat, 500, white) to an object named car:
const car = {type:"Fiat", model:"500", color:"white"};
Objects are containers for Properties and Methods.
Properties are named Values.
Methods are Functions stored as Properties.
Properties can be primitive values, functions, or even other objects.
JavaScript Primitives
A primitive value is a value that has no properties or methods.
3.14 is a primitive value
A primitive data type is data that has a primitive value.
JavaScript defines 7 types of primitive data types:
stringnumberbooleannullundefinedsymbolbigint
Methods for Defining JavaScript Objects
1 Using an Object Literal
2 Using the new Keyword
3 Using an Object Constructor
4 Using Object.assign()
5 Using Object.create()
6 Using Object.fromEntries()
// 1. Creating an object using literal notation
const objLiteral = {
name: "Shamim",
age: 25,
profession: "Developer"
};
console.log(objLiteral); // { name: "Shamim", age: 25, profession: "Developer" }
// 2. Creating an object using the `new` keyword
const objNew = new Object();
objNew.name = "Shamim";
objNew.age = 25;
objNew.profession = "Developer";
console.log(objNew); // { name: "Shamim", age: 25, profession: "Developer" }
// 3. Defining a constructor function
function Person(name, age, profession) {
this.name = name;
this.age = age;
this.profession = profession;
}
// Creating an object using the constructor
const objConstructor = new Person("Shamim", 25, "Developer");
console.log(objConstructor); // Person { name: "Shamim", age: 25, profession: "Developer" }
// 4. Creating an object using Object.assign()
const source = { name: "Shamim", age: 25 };
const additional = { profession: "Developer" };
const objAssign = Object.assign({}, source, additional);
console.log(objAssign); // { name: "Shamim", age: 25, profession: "Developer" }
// 5. Creating an object using Object.create()
const prototypeObj = { greet() { console.log("Hello!"); } };
const objCreate = Object.create(prototypeObj);
objCreate.name = "Shamim";
console.log(objCreate); // { name: "Shamim" }
objCreate.greet(); // "Hello!"
// 6. Creating an object using Object.fromEntries()
const entries = [["name", "Shamim"], ["age", 25], ["profession", "Developer"]];
const objFromEntries = Object.fromEntries(entries);
console.log(objFromEntries); // { name: "Shamim", age: 25, profession: "Developer" }
Common Operations on Objects:
- Accessing Properties:
- Dot Notation: obj.key
- Bracket Notation: obj[key]
- Adding/Updating Properties:
const obj = {};
obj.name = "Shamim";
obj["age"] = 25;
- Deleting Properties:
delete obj.age;
- Iterating Over Properties:
for (let key in obj) {
console.log(key, obj[key]);
}
- Object Methods:
- Object.keys(obj) - Returns an array of property names.
- Object.values(obj) - Returns an array of property values.
- Object.entries(obj) - Returns an array of key-value pairs.
Example: Objects in Action:
const student = {
name: "John",
marks: { math: 90, science: 85 },
greet: function() {
return `Hello, ${this.name}!`;
}
};
console.log(student.greet()); // "Hello, John!"
console.log(student.marks.math); // 90
1. Object.assign()
Purpose: Copies the values of all enumerable properties from one or more source objects to a target object. Useful for cloning or merging objects.
const source = { name: "Shamim", age: 25 };
const additional = { profession: "Developer" };
const objAssign = Object.assign({}, source, additional);
console.log(objAssign); // { name: "Shamim", age: 25, profession: "Developer" }
2. Object.create()
Purpose: Creates a new object with the specified prototype object and properties.
const prototypeObj = { greet() { console.log("Hello!"); } };
const objCreate = Object.create(prototypeObj);
objCreate.name = "Shamim";
console.log(objCreate); // { name: "Shamim" }
objCreate.greet(); // "Hello!"
3. Object.entries()
Purpose: Returns an array of a given object's own enumerable string-keyed property [key, value] pairs.
const person = { name: "Shamim", age: 25 };
const entries = Object.entries(person); console.log(entries); // [["name", "Shamim"], ["age", 25]]
- Use Case: Useful for iterating over an object’s properties.
4. Object.freeze()
Purpose: Freezes an object, preventing new properties from being added and marking all existing properties as read-only.
const person = { name: "Shamim", age: 25 };
Object.freeze(person);
person.age = 30; // This will not work because the object is frozen.
console.log(person); // { name: "Shamim", age: 25 }
- Use Case: Useful for making objects immutable.
5. Object.fromEntries()
Purpose: Converts a list of key-value pairs (such as an array or a Map) into an object.
const entries = [["name", "Shamim"], ["age", 25], ["profession", "Developer"]];
const objFromEntries = Object.fromEntries(entries);
console.log(objFromEntries); // { name: "Shamim", age: 25, profession: "Developer" }
- Use Case: Converts iterable structures like
Mapinto an object.
6. Object.getOwnPropertyDescriptor()
Purpose: Returns the descriptor for a specific property of an object. The descriptor contains metadata like whether the property is writable, enumerable, or configurable.
const person = { name: "Shamim", age: 25 };
const descriptor = Object.getOwnPropertyDescriptor(person, "name");
console.log(descriptor);
// { value: "Shamim", writable: true, enumerable: true, configurable: true }
- Use Case: Useful when you need to inspect the properties of an object.
7. Object.getOwnPropertyNames()
Purpose: Returns an array of all the property names (including non-enumerable properties) of an object.
const person = { name: "Shamim", age: 25 };
const propertyNames = Object.getOwnPropertyNames(person);
console.log(propertyNames); // ["name", "age"]
- Use Case: Useful for listing all properties of an object, including non-enumerable ones.
8. Object.getPrototypeOf()
Purpose: Returns the prototype (i.e., internal [[Prototype]]) of the specified object.
const obj = {};
const prototype = Object.getPrototypeOf(obj);
console.log(prototype); // The prototype of Object
- Use Case: Useful for inspecting the prototype chain of an object.
9. Object.is()
Purpose: Compares two values to determine if they are the same, more accurately than using ===.
console.log(Object.is(25, 25)); // true console.log(Object.is(NaN, NaN)); // true (unlike ===) console.log(Object.is(0, -0)); // false (unlike ===)
- Use Case: Used for more precise comparison, especially with edge cases like
NaNor-0.
10. Object.isExtensible()
Purpose: Determines whether an object is extensible (i.e., whether new properties can be added).
const person = { name: "Shamim" };
console.log(Object.isExtensible(person)); // true
Object.preventExtensions(person);
console.log(Object.isExtensible(person)); // false
- Use Case: Useful for checking if an object can be modified.
11. Object.isFrozen()
Purpose: Checks if an object is frozen (i.e., it cannot have new properties added and all its properties are read-only).
const person = { name: "Shamim" };
Object.freeze(person);
console.log(Object.isFrozen(person)); // true
- Use Case: Useful for checking whether an object is immutable.
12. Object.isSealed()
Purpose: Checks if an object is sealed (i.e., no new properties can be added, but existing properties can still be modified).
const person = { name: "Shamim" };
Object.seal(person);
console.log(Object.isSealed(person)); // true
- Use Case: Useful for checking if an object is sealed and preventing further modifications.
13. Object.keys()
Purpose: Returns an array of a given object's own enumerable property names (keys).
const person = { name: "Shamim", age: 25 };
const keys = Object.keys(person);
console.log(keys); // ["name", "age"]
- Use Case: Used for getting the keys of an object, often in loops or iterating through properties.
14. Object.setPrototypeOf()
Purpose: Sets the prototype (i.e., internal [[Prototype]]) of an object to a specified object or null.
const person = { name: "Shamim" };
const proto = { greet() { console.log("Hello!"); } };
Object.setPrototypeOf(person, proto);
person.greet(); // "Hello!"
- Use Case: Used for modifying the prototype of an object, which can affect inheritance and method lookup.
15. Object.values()
Purpose: Returns an array of a given object's own enumerable property values.
const person = { name: "Shamim", age: 25 };
const values = Object.values(person);
console.log(values); // ["Shamim", 25]
- Use Case: Useful for getting the values of an object, often used in loops or transformations.
Method Purpose
Object.assign() Copies properties from source to target object.
Object.create() Creates a new object with a specified prototype.
Object.entries() Converts an object into an array of key-value pairs.
Object.freeze() Freezes an object (makes it immutable).
Object.fromEntries() Converts a list of key-value pairs into an object.
Object.getOwnPropertyDescriptor() Retrieves the descriptor for a specific property.
Object.getOwnPropertyNames() Gets all properties, including non-enumerable.
Object.getPrototypeOf() Returns the prototype of an object.
Object.is() Compares two values for equality.
Object.isExtensible() Checks if new properties can be added to an object.
Object.isFrozen() Checks if an object is frozen (immutable).
Object.isSealed() Checks if an object is sealed.
Object.keys() Gets all keys of an object.
Object.setPrototypeOf() Sets the prototype of an object.
Object.values() Gets all values of an object.
