Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • Software and Tools
    • School Learning
    • Practice Coding Problems
  • Go Premium
  • 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:
JavaScript Interview Questions and Answers
Next article icon

JavaScript Object Interview Questions

Last Updated : 23 Jul, 2025
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
JavaScript Interview Questions and Answers

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
    JavaScript Interview Questions and Answers
    JavaScript is the most used programming language for developing websites, web servers, mobile applications, and many other platforms. In Both Front-end and Back-end Interviews, JavaScript was asked, and its difficulty depends upon the on your profile and company. Here, we compiled 70+ JS Interview q
    15+ min read
    JavaScript Interview Questions and Answers
    JavaScript is the most used programming language for developing websites, web servers, mobile applications, and many other platforms. In Both Front-end and Back-end Interviews, JavaScript was asked, and its difficulty depends upon the on your profile and company. Here, we compiled 70+ JS Interview q
    15+ min read
    JavaScript Interview Questions and Answers
    JavaScript is the most used programming language for developing websites, web servers, mobile applications, and many other platforms. In Both Front-end and Back-end Interviews, JavaScript was asked, and its difficulty depends upon the on your profile and company. Here, we compiled 70+ JS Interview q
    15+ 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
`; $(commentSectionTemplate).insertBefore(".article--recommended"); } loadComments(); }); }); function loadComments() { if ($("iframe[id*='discuss-iframe']").length top_of_element && top_of_screen articleRecommendedTop && top_of_screen articleRecommendedBottom)) { if (!isfollowingApiCall) { isfollowingApiCall = true; setTimeout(function(){ if (loginData && loginData.isLoggedIn) { if (loginData.userName !== $('#followAuthor').val()) { is_following(); } else { $('.profileCard-profile-picture').css('background-color', '#E7E7E7'); } } else { $('.follow-btn').removeClass('hideIt'); } }, 3000); } } }); } $(".accordion-header").click(function() { var arrowIcon = $(this).find('.bottom-arrow-icon'); arrowIcon.toggleClass('rotate180'); }); }); window.isReportArticle = false; function report_article(){ if (!loginData || !loginData.isLoggedIn) { const loginModalButton = $('.login-modal-btn') if (loginModalButton.length) { loginModalButton.click(); } return; } if(!window.isReportArticle){ //to add loader $('.report-loader').addClass('spinner'); jQuery('#report_modal_content').load(gfgSiteUrl+'wp-content/themes/iconic-one/report-modal.php', { PRACTICE_API_URL: practiceAPIURL, PRACTICE_URL:practiceURL },function(responseTxt, statusTxt, xhr){ if(statusTxt == "error"){ alert("Error: " + xhr.status + ": " + xhr.statusText); } }); }else{ window.scrollTo({ top: 0, behavior: 'smooth' }); $("#report_modal_content").show(); } } function closeShareModal() { const shareOption = document.querySelector('[data-gfg-action="share-article"]'); shareOption.classList.remove("hover_share_menu"); let shareModal = document.querySelector(".hover__share-modal-container"); shareModal && shareModal.remove(); } function openShareModal() { closeShareModal(); // Remove existing modal if any let shareModal = document.querySelector(".three_dot_dropdown_share"); shareModal.appendChild(Object.assign(document.createElement("div"), { className: "hover__share-modal-container" })); document.querySelector(".hover__share-modal-container").append( Object.assign(document.createElement('div'), { className: "share__modal" }), ); document.querySelector(".share__modal").append(Object.assign(document.createElement('h1'), { className: "share__modal-heading" }, { textContent: "Share to" })); const socialOptions = ["LinkedIn", "WhatsApp","Twitter", "Copy Link"]; socialOptions.forEach((socialOption) => { const socialContainer = Object.assign(document.createElement('div'), { className: "social__container" }); const icon = Object.assign(document.createElement("div"), { className: `share__icon share__${socialOption.split(" ").join("")}-icon` }); const socialText = Object.assign(document.createElement("span"), { className: "share__option-text" }, { textContent: `${socialOption}` }); const shareLink = (socialOption === "Copy Link") ? Object.assign(document.createElement('div'), { role: "button", className: "link-container CopyLink" }) : Object.assign(document.createElement('a'), { className: "link-container" }); if (socialOption === "LinkedIn") { shareLink.setAttribute('href', `https://www.linkedin.com/sharing/share-offsite/?url=${window.location.href}`); shareLink.setAttribute('target', '_blank'); } if (socialOption === "WhatsApp") { shareLink.setAttribute('href', `https://api.whatsapp.com/send?text=${window.location.href}`); shareLink.setAttribute('target', "_blank"); } if (socialOption === "Twitter") { shareLink.setAttribute('href', `https://twitter.com/intent/tweet?url=${window.location.href}`); shareLink.setAttribute('target', "_blank"); } shareLink.append(icon, socialText); socialContainer.append(shareLink); document.querySelector(".share__modal").appendChild(socialContainer); //adding copy url functionality if(socialOption === "Copy Link") { shareLink.addEventListener("click", function() { var tempInput = document.createElement("input"); tempInput.value = window.location.href; document.body.appendChild(tempInput); tempInput.select(); tempInput.setSelectionRange(0, 99999); // For mobile devices document.execCommand('copy'); document.body.removeChild(tempInput); this.querySelector(".share__option-text").textContent = "Copied" }) } }); // document.querySelector(".hover__share-modal-container").addEventListener("mouseover", () => document.querySelector('[data-gfg-action="share-article"]').classList.add("hover_share_menu")); } function toggleLikeElementVisibility(selector, show) { document.querySelector(`.${selector}`).style.display = show ? "block" : "none"; } function closeKebabMenu(){ document.getElementById("myDropdown").classList.toggle("show"); }
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
  • DSA Tutorial
  • 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