Objects are one of the most important concepts in JavaScript, allowing you to store collections of data and more complex entities. In this post, we’ll explore what objects are, how to create and manipulate them, and delve into some advanced topics. By the end of this guide, you’ll have a solid understanding of objects in JavaScript.
const javaScriptObject= {};
What are the methods for defining Objects in JavaScript?
You can define/create object using blow methos.
Name | Description | Example |
---|---|---|
Using an Object Literal | Object literals are the most common and straightforward way to create objects. You define the properties and values within curly braces {} . |
|
Using the new Keyword | The new keyword is used to create an instance of an object that is a built-in constructor or a user-defined constructor function. |
|
Using an Object Constructor | An object constructor is a function that initializes an object. You can use it to create multiple instances of an object with the same structure. |
|
Using Object.assign() | Object.assign() is used to copy the values of all enumerable own properties from one or more source objects to a target object. You can use it to create a new object by copying properties from an existing object. |
|
Using Object.create() | Object.create() creates a new object using an existing object as the prototype of the newly created object. This method allows you to implement prototypal inheritance. |
|
Using Object.fromEntries() | Object.fromEntries() creates a new object from an array of key-value pairs (entries). This is particularly useful when converting a Map or array of arrays into an object. |
|
How to access the Object Properties?
In JavaScript, you can access and modify properties of an object using two common methods: dot notation and bracket notation.
Using dot notation:
const car = {
make: "Toyota",
model: "Corolla",
year: 2020,
color: "blue"
};
// Accessing properties using dot notation
console.log(car.make); // Output: Toyota
console.log(car.year); // Output: 2020
// Modifying properties using dot notation
car.color = "red";
console.log(car.color); // Output: red
Using Bracket Notation:
const laptop = {
brand: "Dell",
"operating system": "Windows 10",
memory: "16GB",
"model number": "XPS 15"
};
// Accessing properties using bracket notation
console.log(laptop["operating system"]); // Output: Windows 10
console.log(laptop["model number"]); // Output: XPS 15
// Modifying properties using bracket notation
laptop["memory"] = "32GB";
console.log(laptop["memory"]); // Output: 32GB
Here, the laptop["operating system"]
accesses the property with a space in its name, which cannot be accessed using dot notation.
Can you explain the concept of Prototype Inheritance in JavaScript with example?
In JavaScript, prototype inheritance is a fundamental concept that allows objects to inherit properties and methods from other objects. Here’s a breakdown of how prototype inheritance works in JavaScript:
- Prototype Chain:
- Every JavaScript object has a property called
prototype
. Thisprototype
property is a reference to another object, known as the prototype object. The prototype object itself may have its own prototype, forming a chain of prototypes. - When you access a property or method of an object, JavaScript first looks for it on the object itself. If it’s not found, JavaScript looks up the prototype chain until it either finds the property/method or reaches the end of the chain.
- Every JavaScript object has a property called
- Object Creation:
- When you create an object using a constructor function, that object’s prototype is set to the constructor function’s
prototype
property. This is how properties and methods defined on the constructor’sprototype
are made available to instances of that constructor.
- When you create an object using a constructor function, that object’s prototype is set to the constructor function’s
Example of Prototype Inheritance using Object.create Method
// Constructor function for Animal
function Animal(name) {
this.name = name;
}
// Adding a method to Animal's prototype
Animal.prototype.speak = function() {
console.log(`${this.name} makes a noise.`);
};
// Constructor function for Dog
function Dog(name) {
this.name = name
//OR
//Animal.call(this, name); // Call the Animal constructor with this context
}
// Set up inheritance
Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.constructor = Dog;// to change the constructor property on Dog.prototype by Animal to Dog.
// Creating an instance of Dog
const myDog = new Dog('Rex');
myDog.speak(); // Output: Rex makes a noise.
Example of Prototype Inheritance using Object.setPrototypeOf() Method
// Constructor function for Animal
function Animal(name) {
this.name = name;
}
// Adding a method to Animal's prototype
Animal.prototype.speak = function() {
console.log(`${this.name} makes a noise.`);
};
// Constructor function for Dog
function Dog(name) {
this.name = name; // Initialize the name property
}
// Set up inheritance using Object.setPrototypeOf()
Object.setPrototypeOf(Dog.prototype, Animal.prototype);
// Creating an instance of Dog
const myDog = new Dog('Rex');
myDog.speak(); // Output: Rex makes a noise.
What does Object.assign() do in JavaScript?
Object.assign()
is used to copy the values of all enumerable own properties from one or more source objects to a target object. It returns the target object.
const obj1 = { a: 1, b: 2, x:50 };
let obj2 = { b: 3, c: 4 };
obj2 = Object.assign(obj1, obj2);
console.log(obj2); // {a: 1, b: 3, x: 50, c: 4}
const merged = Object.assign({x:0,y:10}, obj1, obj2);
console.log(merged);// {x: 50, y: 10, a: 1, b: 3, c: 4}
Can Object.assign() be used for deep cloning an object? Why or why not?
No, Object.assign()
cannot be used for deep cloning an object. Object.assign()
only performs a shallow copy of the object’s properties. This means that if an object has nested objects or arrays, Object.assign()
will only copy the references to these nested structures rather than creating new copies of them.
// Original object with nested structure
const original = {
name: 'Alice',
details: {
age: 30,
address: {
city: 'Wonderland'
}
}
};
// Shallow clone using Object.assign()
const shallowClone = Object.assign({}, original);
// Modifying the nested property in the clone
shallowClone.details.address.city = 'New City';
// Checking the original object
console.log(original.details.address.city); // Output: 'New City'
How to deep cloning an object?
Deep cloning an object means creating a new object that is a complete copy of the original, including all nested objects or arrays.
Using JSON.parse
and JSON.stringify
This method is quick and easy but has limitations. It only works for serializable data and will not handle functions, undefined
, or circular references.
const original = {
name: 'Alice',
details: {
age: 30,
address: {
city: 'Wonderland'
}
}
};
// Deep clone using JSON methods
const deepClone = JSON.parse(JSON.stringify(original));
// Modifying the clone does not affect the original
deepClone.details.address.city = 'New City';
console.log(original.details.address.city); // Output: 'Wonderland'
console.log(deepClone.details.address.city); // Output: 'New City'
Using Structured Clone (Modern JavaScript)
The structuredClone
function is a built-in method available in modern browsers and Node.js environments that can clone most objects deeply and handle complex types.
const original = {
name: 'Alice',
details: {
age: 30,
address: {
city: 'Wonderland'
}
}
};
// Deep clone using structuredClone
const deepClone = structuredClone(original);
// Modifying the clone does not affect the original
deepClone.details.address.city = 'New City';
console.log(original.details.address.city); // Output: 'Wonderland'
console.log(deepClone.details.address.city); // Output: 'New City'
Explain the use of Object.create() in JavaScript.
Object.create() creates a new object with the specified prototype object and properties. It is used for setting up prototype-based inheritance.
const animal = {
eat() {
console.log('Eating');
}
};
const dog = Object.create(animal);
dog.bark = function() {
console.log('Barking');
};
dog.eat(); // Output: Eating
dog.bark(); // Output: Barking
What is the use of Object.defineProperties() and How does Object.defineProperties() differ from Object.defineProperty()?
Object.defineProperties() defines new or modifies existing properties directly on an object, returning the object.
Object.defineProperties() allows you to define multiple properties at once on an object, while Object.defineProperty() is used for defining a single property.
You can specify attributes like writable, enumerable, and configurable.
writable: true: Property can be changed
enumerable: true: Property shows up in for..in loops and Object.keys()
configurable: true: Property can be deleted or changed later
const obj = {};
Object.defineProperties(obj, {
property1: {
value: 42,
writable: true, // Property can be changed
enumerable: true, // Property shows up in for..in loops and Object.keys()
configurable: true // Property can be deleted or changed later
},
property2: {
value: "Hello",
writable: false, // Property cannot be changed
enumerable: false, // Property does not show up in for..in loops or Object.keys()
configurable: false // Property cannot be deleted or changed
}
});
console.log(obj.property1); // 42
obj.property1 = 100;
obj.property2 = "JavaScript";
console.log(obj.property1); // 100
console.log(obj.property2); // Hello
console.log(Object.keys(obj)); // ["property1"]
//Object.defineProperty()
Object.defineProperty(obj, 'property3', {
value: 50,
writable: false, // Property cannot be changed
enumerable: true, // Property shows up in for..in loops and Object.keys()
configurable: true // Property can be deleted or changed later
});
console.log(obj.property3); // 50
obj.property3 = 100;
console.log(obj.property3); // 50(because writable is false)
console.log(Object.keys(obj));//['property1', 'property3']
What is the use of Object.entries()?
Object.entries() method returns an array of the key/value pairs of an object. It does not change the original object.
const obj = { a: 1, b: 2, c: 3 };
const entries = Object.entries(obj);
console.log(entries); // [['a', 1], ['b', 2], ['c', 3]]
Can Object.entries() be used on objects with non-enumerable properties? Why or why not?
No, Object.entries() only includes enumerable properties. Non-enumerable properties are not included in the returned array.
// Create an object with enumerable and non-enumerable properties
const obj = {
name: 'Alice',
age: 30,
getName:function () {
return this.name
}
}
// Define a non-enumerable property
Object.defineProperty(obj, 'secret', {
value: 'hidden',
enumerable: false
});
// Use Object.entries() to get entries of the object
const entries = Object.entries(obj);
console.log(entries); // Output: [ [ "name", "Alice" ], [ "age", 30 ], [ "getName", f ] ]
What is the use of Object.values in JavaScript?
The Object.values()
method in JavaScript is used to retrieve an array of an object’s own enumerable property values. This method provides a straightforward way to access the values of an object, excluding properties inherited through the prototype chain.
const data = {
id: 123,
name: 'JavaScript',
active: true,
tags: ['admin', 'user']
};
const values = Object.values(data);
console.log(values);
// Outputs: [123, 'JavaScript', true, ['admin', 'user']]
What does Object.freeze() do, and how is it different from Object.seal()?
Object.freeze() freezes an object, making it immutable. Existing properties cannot be modified, added, or removed.
const obj = { prop: 42 };
Object.freeze(obj);
obj.prop = 100; // No effect
obj.prop2 = 100; // No effect
console.log(obj.prop); // 42
console.log(obj.prop2); // undefined
console.log(obj); // { prop: 42 }
Object.seal() prevents properties from being added or deleted but allows modification of existing properties.
const obj = { prop: 42 };
Object.seal(obj);
obj.prop = 100; // Allowed
obj.prop2 = 100; // No effect
console.log(obj.prop); // 100
console.log(obj.prop2); // undefined
What is the purpose of Object.fromEntries() in JavaScript?
Object.fromEntries() converts a list of key-value pairs (e.g., an array of arrays) into an object.
const entries = [['a', 1], ['b', 2],[5, 3], [null, 0]];
const obj = Object.fromEntries(entries);
console.log(obj); // {5: 3, a: 1, b: 2, null: 0}
Explain the purpose of Object.getOwnPropertyDescriptor() in JavaScript.
Object.getOwnPropertyDescriptor() returns a property descriptor for a named property on an object, including its attributes.
const obj = { prop: 42 };
const descriptor = Object.getOwnPropertyDescriptor(obj, 'prop');
console.log(descriptor.writable); // true
console.log(descriptor.enumerable); // true
Object.defineProperty(obj, 'prop2', {
value: 123,
writable: false,
enumerable: true,
configurable: true
});
const descriptor2 = Object.getOwnPropertyDescriptor(obj, 'prop2');
console.log(descriptor2); //{value: 123, writable: false, enumerable: true, configurable: true}
How does Object.getOwnPropertyDescriptors() differ from Object.getOwnPropertyDescriptor()?
Object.getOwnPropertyDescriptors() returns all own property descriptors for an object, while Object.getOwnPropertyDescriptor() returns a descriptor for a single property.
// Create an object with different properties
const obj = {
name: 'JavaScript',
age: 30
};
// Define a non-enumerable property
Object.defineProperty(obj, 'secret', {
value: 'hidden',
enumerable: false, // This property is not enumerable
writable: true,
configurable: true
});
// Retrieve all property descriptors for the object
const descriptors = Object.getOwnPropertyDescriptors(obj);
console.log(descriptors);
/* output:
{
name: {
value: 'JavaScript',
writable: true,
enumerable: true,
configurable: true
},
age: {
value: 30,
writable: true,
enumerable: true,
configurable: true
},
secret: {
value: 'hidden',
writable: true,
enumerable: false,
configurable: true
}
}*/
What is the use Object.getOwnPropertyNames()?
The getOwnPropertyNames returns an array of all own property names of an object, including non-enumerable properties.
const obj = {'a':500, b:10};
Object.defineProperty(obj, 'hiddenProp', {
value: 42,
enumerable: false
});
const allProps = Object.getOwnPropertyNames(obj);
console.log(allProps);// ['a', 'b', 'hiddenProp']
How does Object.getOwnPropertyNames() differ from Object.keys()?
Object.getOwnPropertyNames() includes non-enumerable properties, while Object.keys() only includes enumerable properties.
What is the proposed Object.groupBy() method in JavaScript?
Object.groupBy() is a proposed method to group elements of an array based on a condition, creating an object where keys are the result of the grouping condition and values are arrays of the grouped elements.
Object.groupby()
is an ES2024 feature. It is fully supported in all modern browsers since March 2024:
const fruits = ['apple', 'banana', 'cherry', 'apricot'];
const groupedByFirstLetter = Object.groupBy(fruits, fruit => fruit[0]);
console.log(groupedByFirstLetter);
// { a: ['apple', 'apricot'], b: ['banana'], c: ['cherry'] }
What does Object.isExtensible() check in an object?
Object.isExtensible() checks whether an object is extensible, meaning whether new properties can be added to it.
const obj = { existing: 1 };
Object.preventExtensions(obj);
console.log(Object.isExtensible(obj)); // false
obj.newProp = 2; // No effect
obj.existing = 2; // Allowed
console.log(obj.newProp); // undefined
console.log(obj); // {existing: 2}
Explain how Object.isFrozen() determines if an object is frozen.
Object.isFrozen() returns true if the object is frozen, meaning it cannot be modified or extended. This includes being non-extensible, with all its properties being non-writable and non-configurable.
const obj = { prop: 42 };
Object.freeze(obj);
console.log(Object.isFrozen(obj)); // true
What are the differences between Object.isFrozen(), Object.isSealed(), and Object.isExtensible()?
Object.isFrozen(): Checks if the object is completely frozen (no modification allowed).
Object.isExtensible(): Checks if new properties can be added to the object.
Object.isSealed(): Checks if the object is sealed (no properties can be added or deleted, but existing properties can be modified).Object.isExtensible(): Checks if new properties can be added to the object.
const obj = { prop: 42 };
Object.seal(obj);
obj.prop = 100; // Allowed
console.log(obj.prop); // 100
Object.isExtensible(): Checks if new properties can be added to the object.
What does Object.keys() return in JavaScript?
Object.keys() in JavaScript returns an array of a given object’s own enumerable property names. It includes only the properties directly on the object and excludes properties inherited through the prototype chain or those that are non-enumerable.
const obj = {
name: 'JavaScript',
age: 30
};
// Define a non-enumerable property
Object.defineProperty(obj, 'secret', {
value: 'hidden',
enumerable: false // This property is not enumerable
});
const keys = Object.keys(obj);
console.log(keys);// Output: ['name', 'age']
What is the purpose of Object.preventExtensions() in JavaScript?
Object.preventExtensions() prevents new properties from being added to an object, but it does not affect the existing properties.
const obj = { existing: 1 };
Object.preventExtensions(obj);
console.log(Object.isExtensible(obj)); // false
obj.newProp = 2; // No effect
obj.existing = 2; // Allowed
console.log(obj.newProp); // undefined
console.log(obj); // {existing: 2}
What is a prototype chain?
In JavaScript, the prototype chain is a mechanism that allows objects to inherit properties and methods from other objects. When you access a property or method on an object, JavaScript first checks the object itself. If it doesn’t find the property or method there, it looks up the prototype chain to find it.
click here to see the example.
How do you check if a key exists in an object?
1. in Operator: The in
operator checks whether a property exists in an object, including properties inherited from the prototype chain.
const obj = { name: 'JavaScript', age: 25 };
console.log('name' in obj); // true
console.log('age' in obj); // true
console.log('address' in obj); // false
2. Object.hasOwnProperty() Method: It checks if a property exists directly on the object itself, excluding properties from the prototype chain.
const obj = { name: 'JavaScript', age: 25 };
console.log(obj.hasOwnProperty('name')); // true
console.log(obj.hasOwnProperty('age')); // true
console.log(obj.hasOwnProperty('address')); // false
3. Object.keys() Method: This method returns an array of the object’s own enumerable property names. You can check if a key exists by seeing if it is included in this array.
const obj = { name: 'JavaScript', age: 25 };
console.log(Object.keys(obj).includes('name')); // true
console.log(Object.keys(obj).includes('age')); // true
console.log(Object.keys(obj).includes('address')); // false
4. Using the undefined Check: You can also check if the value of a property is undefined
, but this approach can be misleading if the property actually exists and its value is explicitly set to undefined
.
const obj = { name: 'JavaScript', age: undefined };
console.log(obj['name'] !== undefined); // true
console.log(obj['age'] !== undefined); // false (but `age` exists)
console.log(obj['address'] !== undefined); // false
Avoid using the undefined check as it can lead to false negatives if a property exists but is explicitly set to undefined.
How do you loop through object in JavaScript?
Method | Purpose | Example |
for...in Loop | Iterates over all enumerable properties, including inherited ones. |
|
Object.keys() with forEach() | The Object.keys() method returns an array of an object’s own enumerable property names. You can use forEach() to iterate over this array. |
|
Object.entries() with forEach() | The Object.entries() method returns an array of [key, value] pairs from an object’s own enumerable properties. You can use forEach() to iterate over these pairs. |
|
Object.values() with forEach() | The Object.values() method returns an array of an object’s own enumerable property values. You can use forEach() to iterate over these values. |
|
for...of Loop with Object.entries() | The for...of loop can be used in combination with Object.entries() to iterate over key-value pairs. |
|
What are the two ways to implement an empty Object?
Method | Description | Method |
---|---|---|
Object Literal | The most straightforward way to create an empty object. | const obj = {}; |
Object Constructor | Creates a new instance of the Object class, resulting in an empty object. | const obj = new Object(); |
How do you copy properties from one object to other?
Method | Description | Method |
---|---|---|
Object.assign() | The Object.assign() method copies all enumerable properties from one or more source objects to a target object. |
|
Spread Syntax | The spread syntax (... ) allows you to create a new object by copying properties from one or more source objects. |
|
How do you define a getter and a setter (Accessors) for an object property in JavaScript?
JavaScript getters and setters are special methods that provide access to object properties., You can define a getter and a setter using the get
and set
keywords within an object literal. Alternatively, you can use Object.defineProperty()
to define them with more control over property attributes.
let persone = {
_name: 'Unknown',
get name() {
return this._name;
},
set name(value) {
this._name = value;
}
};
persone.name = 'JavaScript';
console.log(persone.name);
What will be the Output?
var x = 10, y = 20;
obj = { x, y };
console.log(obj); // {x: 10, y:20} Or Error?
What is destructuring aliases?
Destructuring aliases in JavaScript allow you to extract values from objects or arrays and assign them to variables with different names.
const person = {
firstName: 'John',
lastName: 'Doe'
};
// Destructuring with aliases
const { firstName: fName, lastName: lName } = person;
console.log(fName); // Outputs: John
console.log(lName); // Outputs: Doe
//--------------------
const colors = ['red', 'green', 'blue'];
// Destructuring with custom variable names
const [primaryColor, secondaryColor] = colors;
console.log(primaryColor); // Outputs: red
console.log(secondaryColor); // Outputs: green
click here to know more about destructuring assignment.