Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Array
  • JS String
  • JS Object
  • JS Operator
  • JS Date
  • JS Error
  • JS Projects
  • JS Set
  • JS Map
  • JS RegExp
  • JS Math
  • JS Number
  • JS Boolean
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter
Open In App
Next Article:
Commonly asked JavaScript Interview Questions | Set 1
Next article icon

JavaScript Object Interview Questions

Last Updated : 22 Nov, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

JavaScript objects are fundamental data structures used to store collections of data in key-value pairs. They are essential for handling more complex data and are often used in various JavaScript applications, such as APIs, web development, and data manipulation.

We are going to discuss some JavaScript Object Interview Questions.

1. How do you add dynamic key values in an object?

JavaScript
let dynamicKey = "age";   let dynamicValue = 25;    let user = {};    // Add dynamic key-value pair to the object user[dynamicKey] = dynamicValue;  console.log(user); 

Output
{ age: 25 } 

Explanation: In this code, a new empty object "user" is created. The variable "dynamicKey" is set to the string ""age"", and "dynamicValue" is set to "25". The key-value pair is dynamically added to the "user" object using bracket notation ("user[dynamicKey] = dynamicValue"). This allows the key ""age"" to be set with the value "25". When "console.log(user)" is called, it outputs the object with the dynamic key-value pair: "{ age: 25 }".

2. What will be the output?

JavaScript
const obj = {     a: 1,     b: 2,     a: 3, } console.log(obj); 

Output
{ a: 3, b: 2 } 

Explanation: The object initially has two properties with the same key (a) but different values: first a: 1 and then a: 3. However, in JavaScript, if an object has duplicate keys, the last value for that key will overwrite any previous values. So, the value of a will be set to 3, and the value 1 will be discarded. The final object will contain the key a with the value 3 (overriding the initial a: 1), and the key b with the value 2.

3. Create a function multiplyByTwo(obj) that multiply all the numeric values of nums by 2.

let nums = {
a: 100,
b: 200,
title: "My nums",
};
JavaScript
let nums = {     a: 100,     b: 200,     title: "My nums" };  function multiplyByTwo(obj) {     for (let key in obj) {         if (typeof obj[key] === 'number') {             obj[key] *= 2;  // Multiply numeric values by 2         }     } }  multiplyByTwo(nums); console.log(nums); 

Output
{ a: 200, b: 400, title: 'My nums' } 

Explanation: The multiplyByTwo function takes an object obj as an argument. It iterates through each key of the object using a for...in loop. For each property, it checks if the value is a number (typeof obj[key] === 'number'). If the value is a number, it multiplies that value by 2. After calling multiplyByTwo(nums), the numeric values in the nums object (a and b) are updated, resulting in the object { a: 200, b: 400, title: "My nums" }, while the non-numeric value (title) remains unchanged.

3. What will be the output?

JavaScript
const obj1 = {}; const obj2 = { key: "b" }; const obj3 = { key: "c" }; obj1[obj2] = 123; obj1[obj3] = 234; console.log(obj1[obj2]); 

Output
234 

Explanation: In this code, when you use objects 'obj2' and 'obj3' as keys in the object 'obj1', JavaScript automatically converts these objects into strings using the 'toString()' method. Since both 'obj2' and 'obj3' are objects, their default string representation is '"[object Object]"'. This means both 'obj1[obj2] = 123' and 'obj1[obj3] = 234' actually assign values to the same key: '"[object Object]"'. As a result, the second assignment ('obj1[obj3] = 234') overwrites the first one. Therefore, when you log 'obj1[obj2]', it will return '234', because both 'obj2' and 'obj3' resolve to the same key '"[object Object]"'. The final object 'obj1' will look like '{ "[object Object]": 234 }'.

4. What is JSON.stringify() and JSON.parse() and where do we use it?

JSON.stringify() and JSON.parse() are methods used for converting JavaScript objects to JSON strings and vice versa. JSON.stringify() is used to serialize JavaScript objects into JSON strings, typically when sending data over a network or storing it. JSON.parse() is used to deserialize JSON strings back into JavaScript objects, often when receiving data from a server.

For example, if you want to store a user's settings in local storage, you would first convert the object to a string with JSON.stringify(), then later retrieve and parse it back into an object with JSON.parse().

In this example, JSON.stringify() converts the settings object to a string for storage, and JSON.parse() retrieves and converts the string back into the original object.

JavaScript
// Convert object to JSON string and store in localStorage const settings = { theme: "dark", notifications: true }; localStorage.setItem("userSettings", JSON.stringify(settings));  // Retrieve and convert back to object const storedSettings = JSON.parse(localStorage.getItem("userSettings")); console.log(storedSettings); // Output: { theme: "dark", notifications: true } 

5. What will be the output?

JavaScript
console.log([..."GFG"]); 

Output
[ 'G', 'F', 'G' ] 

Explanation: The expression [....."GFG"] uses the **spread syntax** (...), which unpacks elements from an iterable (in this case, a string) into individual items. Since strings are iterable in JavaScript, the spread syntax spreads the string "GFG" into its individual characters: 'G', 'F', and 'G'. These characters are then placed into a new array, resulting in ['G', 'F', 'G'].

6. What will be the output?

JavaScript
const obj1 = { name: "GFG", age: 14 }; const obj2 = { alpha: "rule", ...obj1 }; console.log(obj2); 

Output
{ alpha: 'rule', name: 'GFG', age: 14 } 

Explanation: The spread syntax (...user) copies all properties from the user object into the new alfa object. The alfa object starts with the property alpha: "rule", and then the properties name: "GFG" and age: 14 are added from the user object. The result is a new object alfa that combines both its own properties and the properties of user.

7. What will be the output?

JavaScript
const obj = {     name: "GFG",     level: 4,     company: true, } const res = JSON.stringify(obj, ["name", "level"]); console.log(res); 

Output
{"name":"GFG","level":4} 

Explanation: In this code, the JSON.stringify() method is used to convert the obj object into a JSON string. The second argument passed to JSON.stringify() is an array of keys (["name", "level"]), which acts as a replacer. This means only the properties specified in the array will be included in the resulting JSON string.

8. What will be the output?

JavaScript
const operation = {     value: 20,     multi() {         return this.value * 10;     },     divide: () => this.value / 10, };  console.log(operation.multi()); console.log(operation.divide()); 

Output
200 NaN 

Explanation: In this code, the "multi" method works correctly because it uses a regular function, where "this" refers to the "operation" object, allowing it to access "this.value" and return "200". However, the "divide" method is an arrow function, which lexically binds "this" to the surrounding context, not the "operation" object. In a browser, "this" inside the arrow function refers to the global object, which doesn't have a "value" property, so "this.value" is "undefined". As a result, "this.value / 10" results in "NaN" because "undefined" divided by 10 is not a valid number.

9. What will be the output?

JavaScript
function Items(list, ...param, list2) {     return [list, ...param, list2]; } Items(["a", "b"], "c", "d"); 

Explanation: The code you provided will result in a syntax error because of the way the parameters are structured in the function definition. In JavaScript, the rest parameter (...param) must be the last parameter in the function definition, but in your code, it is placed before list2, which is not allowed.

10. What will be the output?

JavaScript
let obj1 = { name: "GFG" }; let obj2 = obj1; obj1.name = "GeeksForGeeks"; console.log(obj2.name); 

Output
GeeksForGeeks 

Explanation: Both obj1 and obj2 are pointing to the same object, so when the name property of obj1 is changed to "GeeksforGeeks" that change is reflected in obj2 as well. Therefore, obj2.name will output "GeeksforGeeks".

11. What will be the output?

JavaScript
console.log({ name: "GFG" } == { name: "GFG" }); console.log({ name: "GFG" } === { name: "GFG" }); 

Output
false false 

Explanation: Both '==' and '===' operators compare objects by reference, not by their content. This means that when you compare two objects using either operator, they are considered different if they do not refer to the same memory location, even if their properties are identical. In the case of the code 'console.log({ name: "GFG" } == { name: "GFG" })' and 'console.log({ name: "GFG" } === { name: "GFG" })', both comparisons return 'false' because each object literal creates a new object in memory, so they do not refer to the same object, even though their contents are the same.

12. What will be the output?

JavaScript
let obj1 = { name: "GFG" }; let obj2 = [obj1]; obj1 = null;  console.log(obj2); 

Output
[ { name: 'GFG' } ] 

Explanation: After obj1 is set to null, obj2 still retains the reference to the object, so obj2 will output the array containing the object { name: "GFG" }. The change to obj1 does not affect the obj2 array because arrays and objects in JavaScript are reference types, and obj2 is still holding the reference to the original object.

13. What will be the output?

JavaScript
let obj = { num: 2 }; const fun = (x = { ...obj }) => {     console.log((x.num /= 2)); }  fun(); fun(); fun(obj); fun(obj); 

Output
1 1 1 0.5 

Explanation: The first two calls to fun() create a new object each time (because of the spread operator), and x.num is divided by 2, logging 1 both times. The last two calls pass the original obj as the argument. Since objects are passed by reference, obj is modified directly, first to { num: 1 } and then to { num: 0.5 }. Thus, 1 and 0.5 are logged accordingly.

14. What is shallow copy and deep copy?

A shallow copy creates a new object that shares references to the original object's nested elements, so changes to those elements affect both objects. A deep copy creates a completely independent copy, duplicating all nested objects to avoid shared references.

You can refer to this article for shallow and deep copy.

15. How to deep copy or clone the given object?

To deep copy or clone an object in JavaScript, you can use JSON.stringify() and JSON.parse() methods. This approach serializes the object into a JSON string and then parses it back into a new object, ensuring that nested objects are also copied, rather than just copied by reference.

JavaScript
const original = { name: "John", address: { city: "New York", zip: 10001 } }; const cloned = JSON.parse(JSON.stringify(original));  cloned.address.city = "Los Angeles";  console.log(original.address.city);  console.log(cloned.address.city);     

Output
New York Los Angeles 

In this example, original is an object with a nested object address. By using JSON.stringify() and JSON.parse(), a deep copy of original is created in cloned. Changes made to cloned do not affect original, demonstrating that the nested address object was cloned rather than referenced. This method works well for objects without functions, undefined, or circular references.


Next Article
Commonly asked JavaScript Interview Questions | Set 1

M

meetahaloyx4
Improve
Article Tags :
  • JavaScript
  • Web Technologies
  • javascript-object
  • JavaScript-QnA

Similar Reads

  • JavaScript Output Based Interview Questions
    JavaScript (JS) is the most widely used lightweight scripting and compiled programming language with first-class functions. It is well-known as a scripting language for web pages, mobile apps, web servers, and many more. In this article, we will cover the most asked output-based interview questions
    15+ min read
  • Commonly asked JavaScript Interview Questions | Set 1
    What is JavaScript(JS)? JavaScript is a lightweight, interpreted programming language with object-oriented capabilities that allows you to build interactivity into otherwise static HTML pages.What are the features of JavaScript?JavaScript is a lightweight, interpreted programming language. JavaScrip
    4 min read
  • Core Java Interview Questions For Freshers
    For the latest Java Interview Questions Refer to the Following Article – Java Interview Questions – Fresher and Experienced (2025) Java is one of the most popular and widely used programming languages and a platform that was developed by James Gosling in the year 1995. It is based on the concept of
    15 min read
  • TIAA Interview Experience -Java Back Backend Developer (3+ years Experience)
    Round 1: I was interviewed on Week Days, so there was no company presentation and written test, i was there for round 1 F2F interview, Q1. The very first question was tell me about "FrameTech" which you use in you current project, i was initially confused with the term "FrameTech", he meant the Fram
    2 min read
  • Accolite Interview Experience (Experienced Java Developer)
    Round 1: Coding Round Given an array of integers and a number x, find the smallest subarray with a sum greater than the given value. Find the median of two sorted arrays Round 2: Interview Write a singleton class. Give instances where it is used. https://www.geeksforgeeks.org/singleton-class-java/ S
    1 min read
  • Java Multiple Choice Questions
    Java is a widely used high-level, general-purpose, object-oriented programming language and platform that was developed by James Gosling in 1982. Java Supports WORA(Write Once, Run Anywhere) also, it defined as 7th most popular programming language in the world. Java language is a high-level, multi-
    3 min read
  • Paytm Interview Experience | Set 18 (For 2 Years Experienced)
    Hi all, below are the questions asked in paytm interview for 2yr experienced guy in java technology. I could remember these much only, although there were more questions. Round 1: Explained previous projects. Interfaces vs abstract class interface i1 : void fun() interface i2 : int fun() interface i
    3 min read
  • GE India Interview Questions
    Below is the list of Questions asked in GE interview for a java developer: 1. How to find the 3rd element from end in linked list in Java (Java Program to find the Nth Node from tail in linked list) 2. Write producer consumer problem? 3. wait, notify and notifyall whose methods? 4. Why wait, notify
    2 min read
  • Java Interview Questions and Answers
    Java is one of the most popular programming languages in the world, known for its versatility, portability, and wide range of applications. Java is the most used language in top companies such as Uber, Airbnb, Google, Netflix, Instagram, Spotify, Amazon, and many more because of its features and per
    15+ min read
  • Accolite Digital Interview Experience for Senior Java Developer
    I received the Technical recruiter's direct call for the role of Senior Java Developer - Backend. After initial discussion over the phone call. They scheduled the interview on Turbohire. There were 3 rounds: Technical - Video InterviewManagerial - Video InterviewHR - Telephonic discussion First-roun
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences