In JavaScript, an Object is a non-primitive data type used to store data in key-value pairs.
Objects are one of the most important concepts in JavaScript because almost everything in JavaScript is based on objects.
1. Creating Objects
Using Object Literal (Most Common)
const person = {
name: "John",
age: 25,
city: "New York"
};
console.log(person);
Using new Object()
const person = new Object();
person.name = "John";
person.age = 25;
console.log(person);
2. Accessing Object Properties
Dot Notation
console.log(person.name);
console.log(person.age);
Bracket Notation
console.log(person["name"]);
console.log(person["age"]);
Useful when property names are dynamic.
let key = "name";
console.log(person[key]);
3. Adding Properties
person.country = "USA";
console.log(person);
4. Updating Properties
person.age = 30;
console.log(person.age);
5. Deleting Properties
delete person.city;
console.log(person);
6. Nested Objects
const student = {
name: "Sam",
marks: {
math: 90,
science: 85
}
};
console.log(student.marks.math);
7. Object Methods
Methods are functions inside objects.
const user = {
name: "Alex",
greet: function () {
console.log("Hello");
}
};
user.greet();
Important Object Methods
1. Object.keys()
Returns all object keys.
const person = {
name: "John",
age: 25
};
console.log(Object.keys(person));
Output:
["name", "age"]
2. Object.values()
Returns all values.
console.log(Object.values(person));
Output:
["John", 25]
3. Object.entries()
Returns key-value pairs as arrays.
console.log(Object.entries(person));
Output:
[
["name", "John"],
["age", 25]
]
4. Object.assign()
Copies properties from one object to another.
const obj1 = { a: 1 };
const obj2 = { b: 2 };
const result = Object.assign({}, obj1, obj2);
console.log(result);
Output:
{ a: 1, b: 2 }
5. Object.freeze()
Prevents modification.
const car = {
brand: "BMW"
};
Object.freeze(car);
car.brand = "Audi";
console.log(car.brand);
Output:
BMW
6. Object.seal()
Allows updating existing properties but prevents adding/removing.
const user = {
name: "John"
};
Object.seal(user);
user.name = "Sam"; // allowed
user.age = 30; // not allowed
console.log(user);
7. Object.hasOwn()
Checks if property exists.
const person = {
name: "John"
};
console.log(Object.hasOwn(person, "name"));
Output:
true
8. Object.create()
Creates a new object using another object as prototype.
const animal = {
sound: "Bark"
};
const dog = Object.create(animal);
console.log(dog.sound);
9. Object.fromEntries()
Converts array to object.
const arr = [
["name", "John"],
["age", 25]
];
console.log(Object.fromEntries(arr));
Output:
{
name: "John",
age: 25
}
10. Object.is()
Compares two values.
console.log(Object.is(10, 10));
Output:
true
Looping Through Objects
Using for...in
const person = {
name: "John",
age: 25
};
for (let key in person) {
console.log(key, person[key]);
}
Object Destructuring
const person = {
name: "John",
age: 25
};
const { name, age } = person;
console.log(name);
console.log(age);
Spread Operator with Objects
const obj1 = {
a: 1
};
const obj2 = {
...obj1,
b: 2
};
console.log(obj2);
Shallow Copy vs Reference
Reference Copy
const obj1 = {
name: "John"
};
const obj2 = obj1;
obj2.name = "Sam";
console.log(obj1.name);
Output:
Sam
Shallow Copy
const obj1 = {
name: "John"
};
const obj2 = { ...obj1 };
obj2.name = "Sam";
console.log(obj1.name);
Output:
John
Real-World Example
const employee = {
id: 101,
name: "David",
department: "QA",
skills: ["JavaScript", "Playwright"],
displayInfo() {
console.log(`${this.name} works in ${this.department}`);
}
};
employee.displayInfo();
Common Interview Questions
Difference Between Object and Array
| Object | Array |
|---|---|
| Stores key-value pairs | Stores ordered values |
| Uses keys | Uses indexes |
{} | [] |
Difference Between == and Object.is()
console.log(NaN == NaN); // false
console.log(Object.is(NaN, NaN)); // true
Practice Programs
1. Count Object Properties
const user = {
name: "John",
age: 25,
city: "NY"
};
console.log(Object.keys(user).length);
2. Merge Two Objects
const a = { x: 1 };
const b = { y: 2 };
const c = { ...a, ...b };
console.log(c);
3. Convert Object to Array
const person = {
name: "John",
age: 25
};
console.log(Object.entries(person));
Summary
JavaScript objects are used to:
- Store structured data
- Create reusable methods
- Represent real-world entities
- Manage application state
Most commonly used object methods:
Object.keys()Object.values()Object.entries()Object.assign()Object.freeze()Object.seal()Object.hasOwn()
10 JavaScript Object Programs with Solutions
1. Count Number of Properties in an Object
Problem
Find total number of keys in an object.
Solution
const user = {
name: "John",
age: 25,
city: "New York"
};
const count = Object.keys(user).length;
console.log(count);
Output
3
2. Iterate Through Object Properties
Problem
Print all keys and values from an object.
Solution
const student = {
name: "Sam",
marks: 90,
grade: "A"
};
for (let key in student) {
console.log(key + " : " + student[key]);
}
Output
name : Sam
marks : 90
grade : A
3. Merge Two Objects
Problem
Combine two objects into one.
Solution
const obj1 = {
a: 1,
b: 2
};
const obj2 = {
c: 3,
d: 4
};
const merged = { ...obj1, ...obj2 };
console.log(merged);
Output
{
a: 1,
b: 2,
c: 3,
d: 4
}
4. Check if Property Exists
Problem
Check whether a key exists in object.
Solution
const employee = {
id: 101,
name: "David"
};
console.log("name" in employee);
console.log("salary" in employee);
Output
true
false
5. Remove Property from Object
Problem
Delete a property from object.
Solution
const car = {
brand: "BMW",
color: "Black"
};
delete car.color;
console.log(car);
Output
{
brand: "BMW"
}
6. Convert Object to Array
Problem
Convert object into array of key-value pairs.
Solution
const person = {
name: "John",
age: 30
};
const result = Object.entries(person);
console.log(result);
Output
[
["name", "John"],
["age", 30]
]
7. Find Sum of Object Values
Problem
Calculate sum of numeric values in object.
Solution
const marks = {
math: 90,
science: 80,
english: 85
};
let sum = 0;
for (let key in marks) {
sum += marks[key];
}
console.log(sum);
Output
255
8. Clone an Object
Problem
Create copy of object without affecting original.
Solution
const original = {
name: "Alex",
age: 28
};
const copy = { ...original };
copy.name = "Sam";
console.log(original);
console.log(copy);
Output
{ name: "Alex", age: 28 }
{ name: "Sam", age: 28 }
9. Freeze an Object
Problem
Prevent object modification.
Solution
const user = {
name: "John"
};
Object.freeze(user);
user.name = "Sam";
console.log(user.name);
Output
John
10. Nested Object Access
Problem
Access values inside nested objects.
Solution
const company = {
name: "TechSoft",
employee: {
id: 101,
details: {
name: "David",
role: "QA Engineer"
}
}
};
console.log(company.employee.details.name);
console.log(company.employee.details.role);
Output
David
QA Engineer
Bonus Program — Object Destructuring
Problem
Extract object properties into variables.
Solution
const user = {
name: "John",
age: 25
};
const { name, age } = user;
console.log(name);
console.log(age);
Output
John
25
Concepts Covered
These programs cover:
- Object creation
- Object iteration
- Object methods
- Nested objects
- Destructuring
- Spread operator
- Property checking
- Cloning
- Freezing objects
- Data transformation
Beginner Interview Programs
1. Find the Employee with the Highest Salary
Scenario
A company stores employee details in an object. Find the employee who has the highest salary.
Input
const employees = {
emp1: { name: "John", salary: 55000 },
emp2: { name: "Alice", salary: 72000 },
emp3: { name: "David", salary: 68000 }
};
Expected Output
Highest Salary Employee:
Alice
Salary: 72000
2. Count Product Categories
Scenario
An online shopping website stores products with categories. Count how many products belong to each category.
Input
const products = {
p1: { category: "Electronics" },
p2: { category: "Furniture" },
p3: { category: "Electronics" },
p4: { category: "Books" },
p5: { category: "Books" }
};
Expected Output
Electronics : 2
Furniture : 1
Books : 2
3. Merge Student Information
Scenario
Merge two student objects into one object.
Input
const personal = {
name: "Rahul",
age: 21
};
const academic = {
course: "B.Tech",
marks: 88
};
Expected Output
{
name: "Rahul",
age: 21,
course: "B.Tech",
marks: 88
}
4. Find Missing Properties
Scenario
Check whether every employee object contains an email property.
Input
const employees = {
emp1: {
name: "John",
email: "john@test.com"
},
emp2: {
name: "Alice"
},
emp3: {
name: "David",
email: "david@test.com"
}
};
Expected Output
Employee Missing Email:
Alice
5. Calculate Total Shopping Cart Value
Scenario
Calculate the total bill of all products in the shopping cart.
Input
const cart = {
item1: {
name: "Mouse",
price: 700,
quantity: 2
},
item2: {
name: "Keyboard",
price: 1200,
quantity: 1
},
item3: {
name: "Monitor",
price: 9500,
quantity: 1
}
};
Expected Output
Total Cart Value:
12100
6. Remove Null Values from Object
Scenario
Remove all properties whose value is null.
Input
const user = {
name: "Deepesh",
phone: null,
city: "Bhopal",
email: null,
age: 30
};
Expected Output
{
name: "Deepesh",
city: "Bhopal",
age: 30
}
7. Find Duplicate Values
Scenario
Identify duplicate values present in an object.
Input
const students = {
s1: "A",
s2: "B",
s3: "A",
s4: "C",
s5: "B"
};
Expected Output
Duplicate Values:
A
B
8. Convert Object into Sorted Array
Scenario
Convert the object values into an array and sort them in ascending order.
Input
const marks = {
maths: 78,
science: 91,
english: 65,
computer: 99
};
Expected Output
[65, 78, 91, 99]
9. Update Nested Object
Scenario
Update the city of the employee.
Input
const employee = {
id: 101,
name: "John",
address: {
city: "Delhi",
state: "Delhi"
}
};
Task
Update city to Mumbai.
Expected Output
{
id:101,
name:"John",
address:{
city:"Mumbai",
state:"Delhi"
}
}
10. Find Average Salary
Scenario
Calculate the average salary of all employees.
Input
const employees = {
emp1: { salary: 45000 },
emp2: { salary: 60000 },
emp3: { salary: 75000 },
emp4: { salary: 50000 }
};
Expected Output
Average Salary:
57500
11. Inventory Stock Checker
Scenario
Display all products whose quantity is less than 5.
Input
const inventory = {
p1: { name: "Laptop", quantity: 3 },
p2: { name: "Keyboard", quantity: 8 },
p3: { name: "Mouse", quantity: 2 },
p4: { name: "Monitor", quantity: 10 }
};
Expected Output
Low Stock Products:
Laptop
Mouse
12. Group Employees by Department
Scenario
Group employees based on department.
Input
const employees = {
emp1: { name: "John", department: "IT" },
emp2: { name: "Alice", department: "HR" },
emp3: { name: "David", department: "IT" },
emp4: { name: "Emma", department: "Finance" }
};
Expected Output
{
IT: ["John", "David"],
HR: ["Alice"],
Finance: ["Emma"]
}
13. Find the Most Expensive Product
Scenario
Find the product with the highest price.
Input
const products = {
p1: { name: "Phone", price: 25000 },
p2: { name: "Laptop", price: 65000 },
p3: { name: "Watch", price: 12000 }
};
Expected Output
Laptop
65000
14. Count Boolean Values
Scenario
Count how many properties have true and false values.
Input
const permissions = {
read: true,
write: false,
delete: true,
update: false,
share: true
};
Expected Output
True : 3
False : 2
15. Reverse Key-Value Pairs
Scenario
Swap the keys and values of an object.
Input
const countryCodes = {
India: "IN",
America: "US",
Japan: "JP"
};
Expected Output
{
IN: "India",
US: "America",
JP: "Japan"
}
16. Find Employees Joined After 2022
Scenario
A company stores employee joining years. Display the employees who joined after 2022.
Input
const employees = {
emp1: { name: "John", joiningYear: 2021 },
emp2: { name: "Alice", joiningYear: 2023 },
emp3: { name: "David", joiningYear: 2024 },
emp4: { name: "Emma", joiningYear: 2022 }
};
Expected Output
Employees Joined After 2022
---------------------------
Alice
David
17. Update Product Prices by Percentage
Scenario
An e-commerce application increases all product prices by 10%.
Input
const products = {
p1: { name: "Laptop", price: 50000 },
p2: { name: "Mouse", price: 800 },
p3: { name: "Keyboard", price: 1500 }
};
Expected Output
Updated Prices
Laptop : 55000
Mouse : 880
Keyboard : 1650
18. Find Customers with Premium Membership
Scenario
Display only customers whose membership type is Premium.
Input
const customers = {
c1: { name: "Rahul", membership: "Premium" },
c2: { name: "Amit", membership: "Regular" },
c3: { name: "Neha", membership: "Premium" },
c4: { name: "Priya", membership: "Regular" }
};
Expected Output
Premium Customers
Rahul
Neha
19. Count Active Users
Scenario
Count how many users are active and inactive.
Input
const users = {
u1: { name: "John", active: true },
u2: { name: "Alice", active: false },
u3: { name: "David", active: true },
u4: { name: "Emma", active: true }
};
Expected Output
Active Users : 3
Inactive Users : 1
20. Find the Oldest Employee
Scenario
Find the employee with the maximum age.
Input
const employees = {
emp1: { name: "John", age: 30 },
emp2: { name: "Alice", age: 42 },
emp3: { name: "David", age: 38 },
emp4: { name: "Emma", age: 27 }
};
Expected Output
Oldest Employee
Alice
Age : 42
21. Generate Student Report Card
Scenario
Calculate total, average, percentage, and grade for each student.
Input
const students = {
s1: {
name: "Rahul",
maths: 90,
science: 85,
english: 88
},
s2: {
name: "Priya",
maths: 75,
science: 80,
english: 70
}
};
Expected Output
Student : Rahul
Total : 263
Average : 87.67
Grade : A
---------------------
Student : Priya
Total : 225
Average : 75
Grade : B
22. Find Duplicate Email Addresses
Scenario
Identify duplicate email addresses stored in employee records.
Input
const employees = {
emp1: { email: "john@test.com" },
emp2: { email: "alice@test.com" },
emp3: { email: "john@test.com" },
emp4: { email: "emma@test.com" }
};
Expected Output
Duplicate Emails
john@test.com
23. Sort Employees by Salary
Scenario
Display employees in ascending order of salary.
Input
const employees = {
emp1: { name: "John", salary: 65000 },
emp2: { name: "Alice", salary: 48000 },
emp3: { name: "David", salary: 72000 },
emp4: { name: "Emma", salary: 55000 }
};
Expected Output
Alice : 48000
Emma : 55000
John : 65000
David : 72000
24. Calculate Total Inventory Value
Scenario
Calculate inventory value using price × quantity.
Input
const inventory = {
p1: { name: "Laptop", price: 50000, quantity: 4 },
p2: { name: "Mouse", price: 800, quantity: 15 },
p3: { name: "Keyboard", price: 1500, quantity: 10 }
};
Expected Output
Total Inventory Value
227000
25. Find Employees Working in Multiple Skills
Scenario
Display employees having more than two skills.
Input
const employees = {
emp1: {
name: "John",
skills: ["JavaScript", "React"]
},
emp2: {
name: "Alice",
skills: ["Java", "Spring", "Docker"]
},
emp3: {
name: "David",
skills: ["Python", "Django", "AWS", "Docker"]
}
};
Expected Output
Employees with More Than 2 Skills
Alice
David
26. Create an Employee Directory
Scenario
Convert employee objects into a formatted directory.
Input
const employees = {
emp1: {
name: "John",
phone: "9876543210"
},
emp2: {
name: "Alice",
phone: "9876500000"
}
};
Expected Output
Employee Directory
John - 9876543210
Alice - 9876500000
27. Find Products Above Average Price
Scenario
Display products priced above the average price.
Input
const products = {
p1: { name: "Laptop", price: 60000 },
p2: { name: "Mouse", price: 900 },
p3: { name: "Keyboard", price: 2000 },
p4: { name: "Monitor", price: 18000 }
};
Expected Output
Average Price
20225
Products Above Average
Laptop
Monitor
28. Validate Employee Records
Scenario
Find employees whose records are missing mandatory fields such as name, email, or department.
Input
const employees = {
emp1: {
name: "John",
email: "john@test.com",
department: "IT"
},
emp2: {
name: "Alice",
department: "HR"
},
emp3: {
email: "david@test.com",
department: "Finance"
}
};
Expected Output
Invalid Records
Alice : Missing Email
Employee 3 : Missing Name
29. Compare Two Objects
Scenario
Compare two employee objects and identify differing properties.
Input
const employee1 = {
id: 101,
name: "John",
salary: 50000
};
const employee2 = {
id: 101,
name: "John",
salary: 60000
};
Expected Output
Different Property
salary
Employee1 : 50000
Employee2 : 60000
30. Build a Sales Dashboard
Scenario
Calculate sales statistics for different regions.
Input
const sales = {
north: 250000,
south: 180000,
east: 320000,
west: 210000
};
Expected Output
Total Sales : 960000
Average Sales : 240000
Highest Sales : East (320000)
Lowest Sales : South (180000)