# 🚀 JavaScript Objects — The Ultimate Guide (Beginner to Advanced)

Objects are the heart of JavaScript. Everything in JS is either a **primitive** or an **object-like** structure.

In this blog, we will cover:

✔ Creating Objects  
✔ Accessing & Updating Keys  
✔ Copying Objects (Shallow & Deep)  
✔ Freeze & Seal  
✔ Keys, Values, Entries  
✔ Looping Through Objects  
✔ Object Comparison  
✔ Prototype & Inheritance  
✔ Real-World Recursion Problem  
✔ LeetCode Practice Questions (Solved)

---

# 🟦 Creating an Object

```apache
const person = {
    name: "Vishal",
    age: 21,
    isEducator: true,
    skills: ["C++", "JavaScript", "ReactJS"],
    projects: {
        "Frontend Freaks": "Frontend Development Project",
    },
    code: function(){
        return "start coding";
    },
    walk: () => {
        return "start walking";
    }
}
```

---

# 🟪 Accessing Object Properties

### Using Dot Notation

```apache
console.log(person.age); // 21
```

### Using Bracket Notation

```apache
console.log(person["name"]); // Vishal
```

---

# 🟧 Check if a Key Exists

```apache
console.log(person.hasOwnProperty("name"));      // true
console.log(person.hasOwnProperty("last Name")); // false
```

---

# 🟨 Add, Update, Delete Keys

```apache
person.name = "Vivek";           // Update
person.location = "New Delhi";   // Add
delete person.projects;          // Delete
console.log(person);
```

---

# 🟩 Shallow Copy

```apache
const person2 = person;  
person2.isEducator = false;  // Affects original object
```

---

# 🟦 Deep Copy (Partial)

```apache
const person3 = Object.assign({}, person);
person3.skills = null;
```

⚠️ Note: `Object.assign` only deep-copies 1 level.  
For full deep copy → use **lodash.cloneDeep**.

---

# 🔒 Freeze & Seal

### `freeze()` → No add, delete, update

```apache
Object.freeze(person);
console.log(Object.isFrozen(person)); // true
```

### `seal()` → No add/delete, but update allowed

```apache
Object.seal(person);
console.log(Object.isSealed(person)); // true
```

---

# 🗂 Keys, Values & Entries

```apache
console.log(Object.keys(person));
console.log(Object.values(person));
console.log(Object.entries(person));
```

---

# 🔁 Looping Through an Object

### Using `for…in`

```apache
for (let key in person) {
    console.log(key + ":", person[key]);
}
```

### Using `forEach` with `Object.keys`

```apache
Object.keys(person).forEach((key) => console.log(key));
```

---

# ⚖ Checking Object Equality

```apache
console.log(Object.is(person, person3)); 
```

---

# 🧠 Recursion Example — Count All Players

```apache
const playerCount = (data) => {
    if(data === null) return {};

    let countPlayer = {};

    for(let player of data.name){
        countPlayer[player] = (countPlayer[player] || 0) + 1;
    }

    const nextPlayerCount = playerCount(data.next);

    for(let key in nextPlayerCount){
        countPlayer[key] = (countPlayer[key] || 0) + nextPlayerCount[key];
    }

    return countPlayer;
}
```

---

# 🧬 Prototype & Inheritance

```apache
const obj1 = { name: "Vishal" };

const obj2 = {
    age: 21,
    __proto__: obj1
};

console.log(obj2.name);  // Vishal
```

---

# 🔤 Group Anagrams (LeetCode 49)

```apache
let anagrams = {};

for (let str of strs) {
    const sorted = str.split("").sort().join("");

    if (!anagrams[sorted]) {
        anagrams[sorted] = [];
    }

    anagrams[sorted].push(str);
}

return Object.values(anagrams);
```

---

# 🧩 PRACTICE QUESTIONS (SOLVED)

---

# ✅ 1. Number of Good Pairs

(LeetCode 1512)

Count pairs (i, j) where `nums[i] == nums[j]` and `i < j`.

### ✅ Solution

```apache
var numIdenticalPairs = function(nums) {
    let count = {};
    let goodPairs = 0;

    for (let n of nums) {
        if(count[n]) {
            goodPairs += count[n];
        }
        count[n] = (count[n] || 0) + 1;
    }

    return goodPairs;
};
```

---

# ✅ 2. Count Consistent Strings

(LeetCode 1684)

A word is consistent if all its characters exist in `allowed`.

### Solution

```apache
var countConsistentStrings = function(allowed, words) {
    let set = new Set(allowed);
    let count = 0;

    for (let word of words) {
        let ok = true;

        for (let ch of word) {
            if (!set.has(ch)) {
                ok = false;
                break;
            }
        }
        if (ok) count++;
    }

    return count;
};
```

---

# ✅ 3. Two Sum

(Solved earlier)

```apache
var twoSum = function(nums, target) {
    const map = new Map();

    for (let i = 0; i < nums.length; i++) {
        let complement = target - nums[i];

        if (map.has(complement)) {
            return [map.get(complement), i];
        }
        map.set(nums[i], i);
    }
};
```

---

# ✅ 4. Sum of Unique Elements

(LeetCode 1748)

```apache
var sumOfUnique = function(nums) {
    let freq = {};
    let sum = 0;

    nums.forEach(n => freq[n] = (freq[n] || 0) + 1);

    for (let key in freq) {
        if (freq[key] === 1) sum += Number(key);
    }

    return sum;
};
```

---

# ✅ 5. Unique Number of Occurrences

(LeetCode 1207)

```apache
var uniqueOccurrences = function(arr) {
    let freq = {};

    arr.forEach(n => freq[n] = (freq[n] || 0) + 1);

    let occurrences = new Set(Object.values(freq));

    return occurrences.size === Object.keys(freq).length;
};
```

---

# ✅ 6. Integer to Roman

(LeetCode 12)

```apache
var intToRoman = function(num) {
    const map = [
        [1000, "M"],
        [900, "CM"],
        [500, "D"],
        [400, "CD"],
        [100, "C"],
        [90, "XC"],
        [50, "L"],
        [40, "XL"],
        [10, "X"],
        [9, "IX"],
        [5, "V"],
        [4, "IV"],
        [1, "I"]
    ];

    let result = "";

    for (let [value, symbol] of map) {
        while (num >= value) {
            result += symbol;
            num -= value;
        }
    }

    return result;
};
```

---

# ✅ 7. Longest Substring Without Repeating Characters

(LeetCode 3)

**Sliding window solution**

```apache
var lengthOfLongestSubstring = function(s) {
    let set = new Set();
    let left = 0, max = 0;

    for (let right = 0; right < s.length; right++) {
        while (set.has(s[right])) {
            set.delete(s[left]);
            left++;
        }

        set.add(s[right]);
        max = Math.max(max, right - left + 1);
    }

    return max;
};
```

---

---

# ✅ 8. Find All Anagrams in a String

(LeetCode 438)

```apache
var findAnagrams = function(s, p) {
    if(p.length > s.length) return [];

    let pCount = {};
    let sCount = {};
    let result = [];

    for (let ch of p) {
        pCount[ch] = (pCount[ch] || 0) + 1;
    }

    let left = 0;

    for (let right = 0; right < s.length; right++) {

        sCount[s[right]] = (sCount[s[right]] || 0) + 1;

        if (right - left + 1 === p.length) {

            if (JSON.stringify(sCount) === JSON.stringify(pCount)) {
                result.push(left);
            }

            sCount[s[left]]--;
            if (sCount[s[left]] === 0) delete sCount[s[left]];
            left++;
        }
    }

    return result;
};
```

---

# 🎉 Final Thoughts

This blog covers **everything you need to master JavaScript Objects**, including practical recursion, prototypes, and interview-level challenges.
