Object Static Methods

Back

Loading concept...

πŸ—οΈ Object Static Methods: Your Magical Toolbox

Imagine you have a treasure chest (your object). These static methods are like special tools that help you peek inside, copy treasures, lock the chest, and organize everything perfectly!


🎯 The Big Picture

JavaScript objects are like labeled boxes holding your stuff. Object static methods are helper tools that work on ANY boxβ€”they’re attached to the Object itself, not individual boxes.

Think of it like this: You have a Master Keyring called Object. Each key on this ring does something special to ANY treasure chest you point it at!


πŸ“‹ Object.keys() and Object.values()

The Story

Imagine a toy box with labeled compartments. Object.keys() reads all the labels. Object.values() grabs all the toys inside!

Object.keys() β€” Get All Labels

const pet = {
  name: "Buddy",
  type: "dog",
  age: 3
};

const labels = Object.keys(pet);
// labels = ["name", "type", "age"]

What happened? We got an array of all the property names (keys)!

Object.values() β€” Get All Contents

const pet = {
  name: "Buddy",
  type: "dog",
  age: 3
};

const contents = Object.values(pet);
// contents = ["Buddy", "dog", 3]

What happened? We got an array of all the values inside!

🌟 Real-Life Use

Want to count how many properties? Use Object.keys(pet).length β†’ gives 3!


πŸ”„ Object.entries() and Object.fromEntries()

The Story

Object.entries() is like unpacking a gift box into a list of tags + items. Object.fromEntries() is like repacking that list back into a gift box!

Object.entries() β€” Unpack Into Pairs

const fruit = {
  apple: 5,
  banana: 3
};

const pairs = Object.entries(fruit);
// pairs = [["apple", 5], ["banana", 3]]

Each pair is an array: [key, value]. Super useful for looping!

Object.fromEntries() β€” Pack Pairs Back

const pairs = [
  ["apple", 5],
  ["banana", 3]
];

const fruit = Object.fromEntries(pairs);
// fruit = { apple: 5, banana: 3 }

Magic! We turned an array of pairs back into an object!

🌟 Real-Life Use

Transform data easily:

const prices = { apple: 1, banana: 2 };
const doubled = Object.fromEntries(
  Object.entries(prices).map(
    ([key, val]) => [key, val * 2]
  )
);
// doubled = { apple: 2, banana: 4 }

πŸ“¦ Object.assign() β€” Copy & Merge

The Story

Imagine copying stickers from one notebook to another. Object.assign() copies properties from source objects to a target object!

Basic Copy

const original = { a: 1, b: 2 };
const copy = Object.assign({}, original);
// copy = { a: 1, b: 2 }

The {} is the empty target. We copied everything into it!

Merge Multiple Objects

const base = { a: 1 };
const extra = { b: 2 };
const more = { c: 3 };

const merged = Object.assign({}, base, extra, more);
// merged = { a: 1, b: 2, c: 3 }

⚠️ Watch Out!

Later sources overwrite earlier ones:

const first = { name: "Alice" };
const second = { name: "Bob" };

const result = Object.assign({}, first, second);
// result = { name: "Bob" }  ← Bob wins!

πŸ—οΈ Object.create() β€” Build From Blueprint

The Story

Instead of copying, Object.create() builds a NEW object that β€œinherits” from another objectβ€”like a child learning from a parent!

Basic Usage

const animal = {
  speak() {
    return "Some sound";
  }
};

const dog = Object.create(animal);
dog.bark = function() {
  return "Woof!";
};

dog.speak(); // "Some sound" ← inherited!
dog.bark();  // "Woof!"

The dog can use speak() even though we never defined it on dogβ€”it comes from animal!

🌟 Why Use It?

Perfect for creating object hierarchies without classes. The new object β€œlooks up” to its parent for missing properties.


πŸ”’ Object.freeze() and Object.seal()

The Story

Sometimes you want to protect your treasure chest!

  • Object.freeze() = Locks it completely. Nothing can change!
  • Object.seal() = You can’t add/remove items, but you CAN modify existing ones.

Object.freeze() β€” Total Lockdown

const config = { theme: "dark" };
Object.freeze(config);

config.theme = "light"; // ❌ Ignored!
config.newProp = "hi";  // ❌ Ignored!

// config is still { theme: "dark" }

Object.seal() β€” Partial Protection

const settings = { volume: 50 };
Object.seal(settings);

settings.volume = 80;   // βœ… Works!
settings.newProp = "x"; // ❌ Ignored!
delete settings.volume; // ❌ Ignored!

// settings = { volume: 80 }

Quick Comparison

Action freeze() seal()
Change existing value ❌ No βœ… Yes
Add new property ❌ No ❌ No
Delete property ❌ No ❌ No

βœ… Object.hasOwn() β€” Check Ownership

The Story

Sometimes you need to ask: β€œDoes this object directly own this property?”

Why Not Just Use in?

The in operator checks inherited properties too. Object.hasOwn() only checks the object itself!

const car = { brand: "Toyota" };

Object.hasOwn(car, "brand");     // true
Object.hasOwn(car, "toString");  // false

// But with 'in':
"brand" in car;     // true
"toString" in car;  // true ← inherited!

Modern & Safe

Object.hasOwn() is the modern, recommended way. It’s safer than the old hasOwnProperty method!

const data = { name: "Test" };

// Modern way βœ…
Object.hasOwn(data, "name");

// Old way (still works)
data.hasOwnProperty("name");

πŸ—‚οΈ Object.groupBy() β€” Sort Into Categories

The Story

Imagine sorting your toys into different bins by color. Object.groupBy() does exactly that for arrays!

Basic Example

const fruits = [
  { name: "apple", color: "red" },
  { name: "banana", color: "yellow" },
  { name: "cherry", color: "red" }
];

const grouped = Object.groupBy(
  fruits,
  fruit => fruit.color
);

// grouped = {
//   red: [
//     { name: "apple", color: "red" },
//     { name: "cherry", color: "red" }
//   ],
//   yellow: [
//     { name: "banana", color: "yellow" }
//   ]
// }

How It Works

  1. You give it an array
  2. You give it a function that returns a β€œgroup key”
  3. It sorts items by that key!

🌟 Real-Life Use

Grouping users by role, products by category, or data by date!

const users = [
  { name: "Alice", role: "admin" },
  { name: "Bob", role: "user" },
  { name: "Carol", role: "admin" }
];

const byRole = Object.groupBy(
  users,
  user => user.role
);
// Now admins and users are separated!

🎯 Quick Summary

graph TD A["Object Static Methods"] --> B["keys/values"] A --> C["entries/fromEntries"] A --> D["assign"] A --> E["create"] A --> F["freeze/seal"] A --> G["hasOwn"] A --> H["groupBy"] B --> B1["Get labels or contents"] C --> C1["Convert to/from pairs"] D --> D1["Copy & merge objects"] E --> E1["Inherit from blueprint"] F --> F1["Protect from changes"] G --> G1["Check direct ownership"] H --> H1["Sort into categories"]

πŸš€ You Did It!

You now have a complete toolbox for working with objects in JavaScript:

  • πŸ”‘ keys/values β€” Peek at labels or contents
  • πŸ”„ entries/fromEntries β€” Convert back and forth
  • πŸ“¦ assign β€” Copy and merge
  • πŸ—οΈ create β€” Build from blueprints
  • πŸ”’ freeze/seal β€” Protect your data
  • βœ… hasOwn β€” Check true ownership
  • πŸ—‚οΈ groupBy β€” Organize into categories

You’re now an Object Method Master! πŸŽ‰

Loading story...

Story - Premium Content

Please sign in to view this story and start learning.

Upgrade to Premium to unlock full access to all stories.

Stay Tuned!

Story is coming soon.

Story Preview

Story - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.