31. How do you create objects in JavaScript?
There are several ways to create objects in JavaScript.
1. Object Literal
const user = {
name: "John",
age: 25
};2. new Object()
const user = new Object();
user.name = "Frey";
user.age = 35;
3. Constructor Function
function User(name, age) {
this.name = name;
this.age = age;
}
const user = new User("John", 25);4. Class
class User {
constructor(name, age) {
this.name = name;
this.age = age;
}
}
const user = new User("John", 25);Interview Tip:
Object literals are usually preferred for simple objects, while classes or constructor functions are useful when creating many similar objects.
32. What is object destructuring?
Object destructuring allows you to extract properties from an object and store them in variables.
Example:
const user = {
name: "John",
age: 25,
city: "New York"
};
const { name, age } = user;
console.log(name);
console.log(age);Output:
John
25
Rename Variables:
const { name: userName } = user;
console.log(userName);Default Value:
const { country = "India" } = user;
console.log(country);33. What is the spread operator (...)?
The spread operator expands the elements of an iterable or properties of an object.
Array Example:
const numbers = [1, 2, 3];
const newNumbers = [...numbers, 4, 5];
console.log(newNumbers);
Output:
[1, 2, 3, 4, 5]
Object Example:
const user = {
name: "John",
age: 25
};
const updatedUser = {
...user,
city: "New York"
};Common Uses:
โ Copy arrays
โ Merge arrays
โ Copy objects
โ Merge objects
โ Pass values to functions
34. What is the rest operator?
The rest operator (...) collects multiple values into a single array or object.
Example:
function sum(...numbers) {
return numbers.reduce((total, num) => total + num, 0);
}
console.log(sum(10, 20, 30));Output: 60
Here,
...numbers collects all arguments into an array.Important Interview Point:
The same
... syntax has different purposes:Spread โ expands values:
const arr2 = [...arr1];Rest โ collects values:
function test(...args) {} 35. What are default parameters?
Default parameters allow you to provide a default value when an argument is not passed or is undefined.
Example:
function greet(name = "Guest") {
console.log(`Hello ${name}`);
}
greet();Output: Hello Guest
If a value is provided:
greet("Deepika"); โ Hello Deepika Multiple Defaults:
function createUser(name = "Guest", age = 18) {
console.log(name, age);
}36. What is optional chaining (?. )
Optional chaining allows you to safely access nested properties without throwing an error when an intermediate value is null or undefined.
Without Optional Chaining:
const user = {};
console.log(user.address.city); // ErrorWith Optional Chaining:
console.log(user.address?.city); // undefined