Skip to content

Latest commit

 

History

History
269 lines (199 loc) · 7.75 KB

10.Objects.md

File metadata and controls

269 lines (199 loc) · 7.75 KB

100 JS Questions (Objects)

Q1. What are Objects in JS?

An object is a data type that allows you to store key-value pairs.

Object:

  • String / number / boolen / null / undefined
  • Array
  • Function
  • Object
//Object Example
let person = {
  name: "Happy",
  hobbies: ["Teaching", "Football", "Coding"],
  greet: function() {
    console.log("Name: " + this.name);
  }
};

console.log(person.name); // Output: "Happy"
console.log(person.hobbies[1]); // Output: "Football"
person.greet(); // Output: "Name: Happy"

Q2. In how many ways we can create an object? V. IMP.

Ways to Create and Initialize an Object in JavaScript

Method Syntax Example
Object Literal var objectName = { property1: value1, property2: value2, ... }; var person = { name: "Happy", age: 38, role: "Trainer" };
Object Constructor var objectName = new Object(); var person = new Object();<br>person.name = "Happy";<br>person.age = 38;
Object.create() Method var objectName = Object.create(prototypeObject); var person = { name: "Happy", age: 38 };<br>var men = Object.create(person);<br>men.role = "Trainer";

Q3. What is the difference between array and objects?

Arrays vs. Objects

Feature Arrays Objects
Definition Collections of values. Collections of key-value pairs.
Notation Square brackets []. Curly braces {}.
Element/Property Order Ordered. Unordered.
//Array
var fruits = ["apples", "banana", "orange"]
var person = {
    name: "Adarsh",
    age: 25,
    city: "Delhi"
}

Q4. How do you add or modify or delete properties of an object?

// Blank object
var person = {};
// Adding Properties
person.name = "Happy";
person.age = 35;
person.country = "India";
// Modifying Properties
person.age = 30;
// Deleting Properties
delete person.age;

Q5. Explain the difference between dot notation and bracket notation?

Dot Notation vs. Bracket Notation

  • Both dot notation and bracket notation are used to access properties or methods of an object.

  • Dot notation is more popular and used due to its simplicity.

Limitation of dot notation: In some scenarios, bracket notation is the only option, such as when accessing properties when the property name is stored in a variable.

const person = {
  name: 'Happy',
  age: 35
};

// Dot notation
console.log(person.name); // Output: 'Happy'

// Bracket notation
console.log(person['name']); // Output: 'Happy'
// Dynamically assign property name to a variable
var propertyName = 'age';

// Bracket notation (necessary)
console.log(person[propertyName]); // Output: '35'

// Dot notation (won't work)
console.log(person.propertyName); // Output: undefined

Q6. What are some common methods to iterate over the properties of an object?

Ways to Iterate Over the Properties of an Object

Method Description Example
for...in loop Iterates over the properties of an object. for (let prop in person) { console.log(prop + ": " + person[prop]); }
Object.keys() & forEach() Gets the keys of an object as an array and iterates over them. Object.keys(person).forEach(prop => console.log(prop + ": " + person[prop]));
Object.values() & forEach() Gets the values of an object as an array and iterates over them. Object.values(person).forEach(value => console.log(value));

Q7. How do you check if a property exists in an object?

var person = {
  name: "Alice",
  age: 25
};
// 1. Using the in Operator
console.log("name" in person); // Output: true
console.log("city" in person); // Output: false
// 2. Using the hasOwnProperty() Method
console.log(person.hasOwnProperty("name")); // Output: true
console.log(person.hasOwnProperty("city")); // Output: false
// 3. Comparing with undefined
console.log(person.name !== undefined); // Output: true
console.log(person.city !== undefined); // Output: false

Q8. How do you clone or copy an object?

Method Description Example
Spread Syntax (...) Creates a shallow copy of an object. const clonedObjectSpread = { ...originalObject };
Object.assign() Creates a shallow copy of an object. const clonedObjectAssign = Object.assign({}, originalObject);
JSON.parse() & JSON.stringify() Creates a deep copy of an object, including nested objects and arrays. const clonedObjectJSON = JSON.parse(JSON.stringify(originalObject));

Q9. What is the difference between deep copy and shallow copy in JS?

Shallow Copy vs. Deep Copy in Nested Objects

Shallow Copy (using Object.assign()):

  • Modifies the parent object's property value if the cloned object's property value is changed.

Deep Copy (using JSON.parse() and JSON.stringify()):

  • Does not modify the parent object's property value when the cloned object's property value is changed.

Example:

const person = {
  name: 'Happy',
  age: 30,
  address: {
    city: 'Delhi',
    country: 'India'
  }
};
// Shallow copy using Object.assign()
const shallowCopy = Object.assign({}, person);
shallowCopy.address.city = 'Mumbai';

console.log(person.address.city); // Output: "Mumbai"
console.log(shallowCopy.address.city); // Output: "Mumbai"
// Deep copy using JSON.parse() and JSON.stringify()
const deepCopy = JSON.parse(JSON.stringify(person));
deepCopy.address.city = 'Bangalore';

console.log(person.address.city); // Output: "Delhi"
console.log(deepCopy.address.city); // Output: "Bangalore"

Q10. What is Set Object in JS? V. IMP.

  • Definition: A Set object is a collection of unique values, meaning that duplicate values are not allowed.

  • Methods: Set objects provide methods for adding, deleting, and checking the existence of values in the set.

  • Removing Duplicates from Arrays: Sets can be used to remove duplicate values from arrays by creating a new Set from the array and then converting it back to an array.

// Creating a Set to store unique numbers
const uniqueNumbers = new Set();

uniqueNumbers.add(5);
uniqueNumbers.add(10);
uniqueNumbers.add(5); // Ignore duplicate values

console.log(uniqueNumbers); // Output: { 5, 10 }

// Check size
console.log(uniqueNumbers.size); // Output: 2

// Check element existence
console.log(uniqueNumbers.has(10)); // Output: true

// Delete element
uniqueNumbers.delete(10);
console.log(uniqueNumbers.size); // Output: 1
// Set can be used to remove duplicate values from arrays
let myArr = [1, 4, 3, 4];
let mySet = new Set(myArr);
let uniqueArray = [...mySet];

console.log(uniqueArray); // Output: [1, 4, 3]

Q11. What is Map Object in JS? V. IMP.

The Map object is a collection of key-value pairs where each key can be of any type, and each value can also be of any type. A Map maintains the order of key-value pairs as they were inserted.

Example:

// Creating a Map to store person details
const personDetails = new Map();

personDetails.set("name", "Alice");
personDetails.set("age", 30);

console.log(personDetails.get("name")); // Output: "Alice"
console.log(personDetails.has("age")); // Output: true

personDetails.delete("age");
console.log(personDetails.size); // Output: 1

Q12. What is the difference between Map and Object in JS?

Feature Map JavaScript Object
Keys Can be of any data type (strings, numbers, objects, functions, etc.). Limited to strings and symbols.
Key-Value Pair Order Maintains insertion order. No guaranteed order.
Use Cases Useful when keys are of different types or insertion order is important. Useful when keys are strings or symbols and there are a simple set of properties.