Interview Questions

Browse through our curated collection of questions

How do you check if an object is empty?
Easy
Answer:

 You can use the Object.keys method to get an array of the keys of an object, and then check the length of that array.

const obj = {};
console.log(Object.keys(obj).length === 0); // true
How do you loop over the key-value pairs of an object?
Easy
Answer:

You can use a for...in loop to loop over the keys of an object, and then access the values using bracket notation.

const obj = {a: 1, b: 2};
for (const key in obj) {
  console.log(key, obj[key]);
}
How do you loop over the values of an object?
Easy
Answer:

You can use the Object.values method to get an array of the values of an object, and then loop over that array.

const obj = {a: 1, b: 2};
const values = Object.values(obj);
for (const value of values) {
  console.log(value);
}
How do you loop over the keys of an object?
Easy
Answer:

You can use a for...in loop to loop over the keys of an objet

const obj = {a: 1, b: 2};
for (const key in obj) {
  console.log(key);
}
How do you remove a property from an object?
Easy
Answer:

You can use the delete keyword to remove a property from an object.

const obj = {a: 1, b: 2};
delete obj.b;
console.log(obj);
How do you add a property to an object?
Easy
Answer:

You can simply assign a value to a new or existing property of an object.

const obj = {a: 1};
obj.b = 2;
console.log(obj); // {a: 1, b: 2}
How do you check if an object has a specific property?
Easy
Answer:

You can use the hasOwnProperty method to check if an object has a specific property.

const obj = {a: 1, b: 2};
console.log(obj.hasOwnProperty('a')); // true
console.log(obj.hasOwnProperty('c')); // false
How do you add an element to the end of an array?
Easy
Answer:

You can use the push method to add an element to the end of an array.

const arr = [1, 2, 3];
arr.push(4);
console.log(arr); // [1, 2, 3, 4]
How do you add an element to the beginning of an array?
Easy
Answer:

You can use the unshift method to add an element to the beginning of an array.

const arr = [1, 2, 3];
arr.unshift(0);
console.log(arr); // [0, 1, 2, 3]
How do you remove an element from an array?
Easy
Answer:

You can use the splice method to remove an element from an array. The first argument is the index of the element to be removed, and the second argument is the number of elements to be removed.

const arr = [1, 2, 3];
arr.splice(1, 1); // remove element at index 1
console.log(arr); // [1, 3]