10 JavaScript Objects Interview Questions and Answers
Prepare for your next interview with our guide on JavaScript objects, featuring common questions and detailed answers to boost your confidence.
Prepare for your next interview with our guide on JavaScript objects, featuring common questions and detailed answers to boost your confidence.
JavaScript objects are a fundamental aspect of the language, enabling developers to create complex data structures and manage state effectively. As a versatile and widely-used language, JavaScript’s object-oriented capabilities are crucial for building dynamic web applications, handling asynchronous operations, and ensuring code modularity and reusability. Mastery of JavaScript objects is essential for any developer aiming to work on modern web development projects.
This article provides a curated selection of interview questions focused on JavaScript objects, designed to help you demonstrate your understanding and proficiency in this key area. By reviewing these questions and their detailed answers, you will be better prepared to showcase your skills and knowledge in technical interviews, enhancing your prospects in the competitive job market.
greet
to an object person
that logs “Hello, my name is [name]”? Provide a code example.In JavaScript, objects are collections of properties, where a property is an association between a name (or key) and a value. Methods are functions stored as object properties. To add a method to an existing object, assign a function to a property of that object.
Here’s how to add a greet
method to a person
object:
let person = { name: 'John' }; person.greet = function() { console.log(`Hello, my name is ${this.name}`); }; person.greet(); // Output: Hello, my name is John
name
and age
from an object user
.Object destructuring allows you to unpack properties from objects into distinct variables, which is useful for handling complex objects or passing multiple properties as function parameters.
Example:
const user = { name: 'John Doe', age: 30, email: '[email protected]' }; const { name, age } = user; console.log(name); // John Doe console.log(age); // 30
In this example, name
and age
are extracted from the user
object and assigned to variables with the same names, making the code more concise.
Prototypal inheritance in JavaScript allows objects to inherit properties and methods from other objects through the prototype chain. This mechanism enables code reuse and the creation of complex objects based on simpler ones.
Example:
function Person(name, age) { this.name = name; this.age = age; } Person.prototype.greet = function() { console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`); }; function Student(name, age, grade) { Person.call(this, name, age); this.grade = grade; } Student.prototype = Object.create(Person.prototype); Student.prototype.constructor = Student; Student.prototype.study = function() { console.log(`${this.name} is studying.`); }; const student1 = new Student('Alice', 20, 'A'); student1.greet(); // Hello, my name is Alice and I am 20 years old. student1.study(); // Alice is studying.
In this example, the Person
constructor function defines a greet
method on its prototype. The Student
constructor function inherits from Person
using Object.create
to set up the prototype chain.
Animal
with a constructor that initializes name
and species
properties. Add a method speak
that logs “[name] makes a noise”. Show how to instantiate this class.To create a class Animal
in JavaScript, use the class
keyword. The constructor method initializes the name
and species
properties. Add a method speak
that logs a message indicating the animal makes a noise.
class Animal { constructor(name, species) { this.name = name; this.species = species; } speak() { console.log(`${this.name} makes a noise`); } } // Instantiating the class const dog = new Animal('Buddy', 'Dog'); dog.speak(); // Output: Buddy makes a noise const cat = new Animal('Whiskers', 'Cat'); cat.speak(); // Output: Whiskers makes a noise
#
syntax.In JavaScript, private properties and methods can be created using closures or the #
syntax, providing encapsulation.
Using closures:
function Person(name) { let _name = name; // private property this.getName = function() { return _name; // public method accessing private property }; } const person = new Person('John'); console.log(person.getName()); // John console.log(person._name); // undefined
Using the #
syntax:
class Person { #name; // private property constructor(name) { this.#name = name; } getName() { return this.#name; // public method accessing private property } } const person = new Person('John'); console.log(person.getName()); // John console.log(person.#name); // SyntaxError: Private field '#name' must be declared in an enclosing class
Object.freeze
and Object.seal
. Provide examples showing how each one works.Object.freeze
and Object.seal
control the mutability of objects in different ways.
– Object.freeze
: Makes an object immutable. You cannot add, remove, or modify its properties.
– Object.seal
: Prevents new properties from being added and marks all existing properties as non-configurable, but allows modification of existing properties.
Example of Object.freeze
:
const obj = { name: "Alice" }; Object.freeze(obj); obj.name = "Bob"; // This will not change the name property obj.age = 30; // This will not add a new property console.log(obj); // Output: { name: "Alice" }
Example of Object.seal
:
const obj = { name: "Alice" }; Object.seal(obj); obj.name = "Bob"; // This will change the name property obj.age = 30; // This will not add a new property console.log(obj); // Output: { name: "Bob" }
Object.defineProperty
to create a non-writable property. Provide an example.Object.defineProperty
allows you to define or modify a property on an object with detailed control over the property’s behavior. To create a non-writable property, set the writable
attribute to false
.
Example:
const obj = {}; Object.defineProperty(obj, 'nonWritableProp', { value: 'This value cannot be changed', writable: false, configurable: true, enumerable: true }); console.log(obj.nonWritableProp); // Output: This value cannot be changed obj.nonWritableProp = 'Attempt to change value'; console.log(obj.nonWritableProp); // Output: This value cannot be changed
In this example, the property nonWritableProp
is defined on the object obj
with a value that cannot be changed.
The spread operator, denoted by three dots (…), allows for the expansion of iterable elements such as arrays and objects. When used with objects, it can merge two or more objects into a single object.
Example:
const obj1 = { a: 1, b: 2 }; const obj2 = { c: 3, d: 4 }; const mergedObj = { ...obj1, ...obj2 }; console.log(mergedObj); // Output: { a: 1, b: 2, c: 3, d: 4 }
Optional chaining, denoted by the ?.
operator, short-circuits and returns undefined
if any part of the chain is null
or undefined
, making it useful for accessing nested properties.
Example:
const user = { name: 'John', address: { city: 'New York', zip: '10001' } }; console.log(user?.address?.city); // 'New York' console.log(user?.contact?.phone); // undefined
In the example above, user?.address?.city
safely accesses the city
property of the address
object. If address
were null
or undefined
, it would return undefined
.
Object.entries
to iterate over an object’s key-value pairs? Provide an example.Object.entries
returns an array of a given object’s own enumerable string-keyed property [key, value] pairs. This method is useful for iterating over an object’s key-value pairs using loops such as for...of
.
Example:
const user = { name: 'Alice', age: 30, city: 'New York' }; for (const [key, value] of Object.entries(user)) { console.log(`${key}: ${value}`); }
In this example, Object.entries(user)
converts the user
object into an array of key-value pairs, which is then iterated over using a for...of
loop.