Skip to main content

Command Palette

Search for a command to run...

πŸš€ JavaScript Objects β€” The Ultimate Guide (Beginner to Advanced)

πŸš€ JavaScript Objects

Published
β€’5 min readβ€’View as Markdown
πŸš€ 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

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

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

Using Bracket Notation

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

🟧 Check if a Key Exists

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

🟨 Add, Update, Delete Keys

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

🟩 Shallow Copy

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

🟦 Deep Copy (Partial)

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

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

seal() β†’ No add/delete, but update allowed

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

πŸ—‚ Keys, Values & Entries

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

πŸ” Looping Through an Object

Using for…in

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

Using forEach with Object.keys

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

βš– Checking Object Equality

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

🧠 Recursion Example β€” Count All Players

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

const obj1 = { name: "Vishal" };

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

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

πŸ”€ Group Anagrams (LeetCode 49)

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

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

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)

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)

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)

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)

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

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)

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.