JavaScript Course

Object Methods Object.keys Object.values and many others

Object Creation and Accessing Properties

Creating Objects:

Objects are created using curly braces {}, and each property is represented as a key-value pair, separated by a colon. For example:

const person = {
  name: "John Doe",
  age: 30,
};

Accessing Properties:

You can access object properties using dot notation or square brackets. Dot notation is more concise, while square brackets allow for dynamic property names. For example:

const name = person.name; // Dot notation
const age = person["age"]; // Square brackets

Tips for Memorization:

  • Think of objects as virtual containers that hold key-value pairs.
  • Visualize dot notation as the direct path to a property, like following a GPS route.
  • Use square brackets when accessing dynamic property names that may change at runtime.

Stay tuned for the next part where we'll delve into Object Properties and Methods!

Object Properties and Methods

Properties and Methods: A Dynamic Duo

Objects aren't just collections of properties; they're powerhouses of action with methods! Methods are like functions attached to objects, giving them special abilities.

Think of objects as cars. Properties are the car's features (color, speed), while methods are its actions (drive, park).

Object.keys(), Object.values(), and Object.entries()

These three methods are your gatekeepers to the object's properties.

  • Object.keys(): Returns an array of all property names (like ['color', 'speed']).
  • Object.values(): Returns an array of all property values (like ['red', 100]).
  • Object.entries(): Returns an array of key-value pairs (like [['color', 'red'], ['speed', 100]]).

Object.assign(), Object.freeze(), and Object.seal()

These methods give you control over the mutability (changeability) of objects.

  • Object.assign(): Copies properties from one object to another (like merging two cars).
  • Object.freeze(): Makes an object immutable (like freezing a car in place).
  • Object.seal(): Makes an object's properties immutable but allows adding new ones (like freezing the car's features but letting it move).

... Stay tuned for more methods and techniques that will make your objects dance!

Object.keys()

What is it?

The Object.keys() method returns an array of all the property names in an object.

Why is it useful?

This method is useful for iterating over the properties of an object and performing operations on each property name.

How to use it:

To use the Object.keys() method, simply pass an object to the method as a parameter. For example:

const person = {
  name: "John Doe",
  age: 30,
  city: "New York",
};

const propertyNames = Object.keys(person);

console.log(propertyNames);

This will output the following array:

["name", "age", "city"]

Tips for memorization:

  • Remember that the Object.keys() method returns an array of property names, not the values.
  • Visualize the Object.keys() method as a tool that extracts the keys from an object and stores them in an array.

Stay tuned for the next section, where we'll explore the Object.values() method!

Object.values()

Understanding Object.values()

The Object.values() method grabs an array of all the values within a given object. It's like having a treasure chest full of values, ready for you to explore!

Practical Ways to Remember

  • Visualize the Object.values() method as a secret key that unlocks the values hidden within an object.
  • Imagine the values as precious gems, waiting to be discovered.
  • Remember that Object.keys() gives you property names, while Object.values() provides the treasures inside.

Sample Code Example

const treasureChest = {
  gold: 100,
  gems: ["emerald", "ruby", "sapphire"],
  maps: ["treasure map", "lost city map"],
};

const values = Object.values(treasureChest);

console.log(values); // Output: [100, ["emerald", "ruby", "sapphire"], ["treasure map", "lost city map"]]

What's Next?

Hold your breath for the next adventure - Object.entries(), where we'll reveal both keys and values as a magical duo!

Object.entries() - Unveiling the Key-Value Pairs

The Object.entries() method is your gateway to a world of key-value pairs! It takes an object as its trusty companion and returns an array of arrays, each containing a key and its corresponding value.

Think of it like a map where the first element in each array is the street name (key), and the second element is the house number (value).

To use this magical method, simply pass your object as a secret message:

const object = {
  name: "Captain Jack",
  treasure: "Gold doubloons",
};
const keyValuePairs = Object.entries(object);

And behold, the keyValuePairs will hold an array of arrays like this:

[["name", "Captain Jack"], ["treasure", "Gold doubloons"]]

Tips for Mastery:

  • Visualize Object.entries() as a treasure hunter, searching for matching keys and values.
  • Remember, it returns an array of arrays, not just an array of values or keys.
  • Use this method to iterate over both keys and values simultaneously.

What's Next?

Prepare your compass and set sail for the next captivating adventure: Object.assign(), where objects merge and treasures unite!

Object.assign()

Hey there, JavaScript adventurers! πŸ—ΊοΈ Get ready to dive into the fascinating realm of Object.assign().

What is Object.assign()?

Think of Object.assign() as a magical cloning machine that allows you to create a new object by merging properties from one or more existing objects. It's like combining the powers of two or more superheroes into one super object!

Benefits of Object.assign()

  • Clone Objects: Quickly and easily create a copy of an object without modifying the original. This is especially useful when you need to preserve data or perform operations without altering the source.
  • Merge Objects: Combine properties from multiple objects into a single new object. This simplifies the process of creating complex objects by breaking them down into smaller, manageable chunks.
  • Extend Objects: Add or override properties in an existing object without mutating the original. This allows you to customize objects dynamically and extend their functionality.

Syntax:

Object.assign(targetObject, sourceObject1, sourceObject2, ...);
  • targetObject: The object that will receive the merged properties.
  • sourceObject1, sourceObject2, ...: The objects whose properties will be copied into the target object.

Example:

const obj1 = { name: "John", age: 30 };
const obj2 = { city: "New York" };

const mergedObj = Object.assign({}, obj1, obj2);

console.log(mergedObj); // Output: { name: "John", age: 30, city: "New York" }

Tips for Memorization:

  • Think of a Blueprint: Object.assign() acts like a blueprint, merging the properties of different objects to create a new one.
  • Use an Analogy: Imagine you have three baskets, each containing different fruits. Object.assign() is like pouring the fruits from all the baskets into a new, bigger basket.
  • Remember the Parameters: The first parameter is always the target object, and the rest are the source objects to be merged.

Stay Curious:

Hold your excitement, explorers! We've only scratched the surface of Object.assign(). In the next thrilling installment, we'll venture into the depths of Object.freeze(), where objects become unchangeable and their properties remain forever frozen in time... ❄️

Object.freeze()

What's Object.freeze()?

Think of Object.freeze() as a magic spell that locks an object, making it unchangeable πŸ”’. Once frozen, you can't add, remove, or modify any properties. It's like putting an object in a time capsule, preserving it for eternity.

Why Use Object.freeze()?

  • Data Integrity: Prevent accidental or malicious changes to critical data.
  • Performance Optimization: Frozen objects can be stored in memory more efficiently, improving performance.
  • Security Enhancement: Protect sensitive data from being tampered with.

How to Use Object.freeze():

It's as simple as casting the freeze spell:

const frozenObject = Object.freeze({
  name: "John Doe",
  age: 30,
});

Now, frozenObject is sealed in time. Let's try to modify it:

frozenObject.name = "Jane Doe"; // Oops, won't work!
delete frozenObject.age; // Nope, can't delete it either

The object remains unscathed, its properties untouched.

Tips for Memorization:

  • Visualize the Ice Castle: Picture an ice castle where objects are frozen in blocks of ice. Object.freeze() builds this castle around your object.
  • Remember the Freeze Command: Type the magical incantation Object.freeze() to cast the spell.
  • See the Error Message: When you try to change a frozen object, JavaScript will throw an error. This will remind you that the object is protected.

Stay Tuned:

In the next thrilling episode, we'll explore Object.seal(), where objects are semi-frozen, allowing you to add properties but not modify existing ones. It's like a magical shield that protects your object from some changes, leaving it partially flexible... ✨

Object.seal()

What is Object.seal()?

Picture Object.seal() as a semi-protective shield for your objects. It allows you to add new properties, but once added, they become unchangeable. Existing properties remain untouched. It's like a guarded fortress, where entry is granted but modifications are forbidden.

Why Use Object.seal()?

  • Controlled Mutability: You can add new properties when needed, while preventing unintended changes to existing ones.
  • Partial Protection: It offers a middle ground between complete immutability (Object.freeze()) and full mutability.
  • Performance Optimization: Sealed objects can be stored more efficiently, improving performance.

How to Use Object.seal():

Seal your objects with this magic spell:

const sealedObject = Object.seal({
  name: "John Doe",
  age: 30,
});

Now, sealedObject is semi-protected. Let's try to modify it:

sealedObject.name = "Jane Doe"; // Oops, can't change it!
sealedObject.job = "Software Engineer"; // Hey, I can add a new property!

The existing property "name" remains untouched, while the new property "job" is successfully added.

Tips for Memorization:

  • Visualize the Guarded Fortress: Imagine a fortress with a drawbridge for new properties. Once inside, the bridge is raised, preventing changes to existing properties.
  • Remember the Semi-Protection: Object.seal() allows additions but not modifications.
  • See the Output: When you try to change a sealed property, you'll get an error. This serves as a visual reminder of the protection in place.

What's Next?

Buckle up for Object Spread Operator, the next adventure in our object manipulation journey!

Object Spread Operator

What is the Object Spread Operator?

Imagine the object spread operator as a superpower that allows you to create a new object by spreading out the properties of one or more existing objects. It's like a magical cloning machine that lets you duplicate an object with ease.

Benefits of Using the Object Spread Operator:

  • Easy Cloning: Quickly create a copy of an object without modifying the original.
  • Property Merging: Combine properties from multiple objects into a single new object.
  • Object Extension: Add or override properties in an existing object.

Syntax:

const newObject = {...object1, ...object2, ...object3};
  • newObject: Represents the new object that will be created.
  • object1, object2, object3: The objects whose properties will be spread into the new object.

Example:

const obj1 = { name: "John", age: 30 };
const obj2 = { city: "New York" };

const newObj = {...obj1, ...obj2};

console.log(newObj); // Output: { name: "John", age: 30, city: "New York" }

Tips for Memorization:

  • Think of a Chef: Visualize the spread operator as a chef who combines ingredients from different dishes to create a new and delicious meal.
  • Use an Analogy: Imagine you have three boxes of toys. The spread operator lets you empty all the toys from the boxes into a new box, combining them together.
  • Create a Mnemonic: Remember the phrase "Spread the Properties like a Boss."

Stay Curious:

Prepare to embark on the exciting next adventure in our object manipulation journey: Destructuring Objects!

Destructuring Objects

Destructuring Made Easy

Imagine you're on a treasure hunt, and you find a chest filled with keys and values. Destructuring objects is like having a magical key that unlocks the treasure of an object's properties. It lets you access and assign those properties to variables with much more ease!

Unlocking Property Values

To destructure an object, use this syntax:

const { property1, property2, ... } = object;
  • object is the treasure chest you're opening.
  • property1, property2, etc. are the keys to the treasures you want to unlock.

For example:

const person = { name: "John", age: 30 };

const { name, age } = person;

console.log(name); // outputs "John" console.log(age); // outputs 30

Avoiding Repetitions

Remember, destructuring avoids the need for repetitive code like:

const name = person.name;
const age = person.age;

Focus on Property Names

When destructuring, focus on the property names you need, not the entire object. This helps keep your code concise and readable.

Going a Step Further

You can also use the special syntax "...rest" to collect the remaining properties into a single variable:

const { property1, property2, ...rest } = object;

This is useful when you have many properties in an object and only need a few.

Let's Practice

Try this example:

const student = { id: 123, name: "Mary", grade: "A" };

const { name, id } = student;

console.log(name); // outputs "Mary" console.log(id); // outputs 123

Looking Ahead

Now that you've mastered the basics, prepare for the next adventure: Comparing Objects!

Comparing Objects

In the realm of JavaScript, comparing objects can be a tricky task. But fear not, for this guide will equip you with practical methods to navigate this challenge.

Tips for Memorization

  • Visualize a Scale: Imagine objects as being placed on a scale. If they have the same properties and values, the scale will balance; otherwise, it will tilt.
  • Use a Table: Create a table with the properties of both objects and compare them one by one to spot any differences.

How to Compare Objects

1. Object.keys(): This method returns an array of the object's own property names. By comparing the arrays, you can check if the objects have the same properties.

2. Object.values(): Similar to Object.keys(), this method returns an array of the object's own property values. Compare the arrays to see if the objects have the same values.

3. Object.entries(): This method returns an array of arrays, where each inner array contains a property name and its corresponding value. Comparing these arrays allows you to check both properties and values simultaneously.

Examples

const obj1 = { name: "John", age: 30 };
const obj2 = { first_name: "John", last_name: "Doe", age: 30 };

// Checking for same properties using Object.keys() const obj1Keys = Object.keys(obj1); const obj2Keys = Object.keys(obj2); const areKeysSame = obj1Keys.length === obj2Keys.length && obj1Keys.every(key => obj2Keys.includes(key));

// Checking for same values using Object.values() const obj1Values = Object.values(obj1); const obj2Values = Object.values(obj2); const areValuesSame = obj1Values.length === obj2Values.length && obj1Values.every(val => obj2Values.includes(val));

// Checking for same properties and values using Object.entries() const obj1Entries = Object.entries(obj1); const obj2Entries = Object.entries(obj2); const areEntriesSame = obj1Entries.length === obj2Entries.length && obj1Entries.every(([key1, val1], i) => [key1, val1] === obj2Entries[i]);

console.log("Are obj1 and obj2 the same?"); console.log(Properties: ${areKeysSame}); console.log(Values: ${areValuesSame}); console.log(Both properties and values: ${areEntriesSame});

Iterating Objects

As we close this chapter on comparing objects, we invite you to embark on a new adventure: Iterating Objects. Stay tuned to unravel the secrets of traversing objects and unlocking their inner workings!

Iterating Objects

Dive into the magical world of iterating objects, where you'll learn how to explore the properties and values of objects one by one. It's like opening a treasure chest filled with knowledge!

Key Concepts

  • Iteration: Going through each item in a sequence, one at a time.
  • Object: A collection of properties and values that represent a real-world entity.

Methods for Iterating Objects

  • for...in: Iterates over the keys (property names) of an object.
  • Object.keys(object): Returns an array of an object's keys.
  • Object.values(object): Returns an array of an object's values.
  • Object.entries(object): Returns an array of arrays, where each array contains a key and its corresponding value.

Practical Examples

for...in

const person = { name: "John", age: 30 };

for (const key in person) { console.log(${key}: ${person[key]}); }

// Output: // name: John // age: 30

Object.keys()

const keys = Object.keys(person);

keys.forEach((key) => { console.log(person[key]); });

// Output: // John // 30

Object.values()

const values = Object.values(person);

values.forEach((value) => { console.log(value); });

// Output: // John // 30

Object.entries()

const entries = Object.entries(person);

entries.forEach(([key, value]) => { console.log(${key}: ${value}); });

// Output: // name: John // age: 30

Tips for Memorization

  • Visualize the Treasure Chest: Imagine an object as a treasure chest filled with key-value pairs.
  • Use a Table: Create a table with two columns: Keys and Values. Fill it with the properties and values from the object.
  • Remember the Methods:
    • for...in: Iterate over keys
    • Object.keys(): Get an array of keys
    • Object.values(): Get an array of values
    • Object.entries(): Get an array of [key, value] pairs

Where to Go Next: Prototype Chain and Inheritance

Now that you've mastered object iteration, prepare for an exciting journey through the world of Prototype Chain and Inheritance. Stay tuned to discover how objects can inherit properties and methods from other objects, just like a royal family lineage!

Prototype Chain and Inheritance

What is the Prototype Chain?

Imagine objects as a royal family. Each object has its own properties and methods, like unique traits. However, they also inherit traits from their ancestors. This is called the prototype chain.

Inheritance in JavaScript

JavaScript allows objects to inherit properties and methods from other objects. This is similar to how children inherit traits from their parents.

How Inheritance Works

When you create a new object, it inherits from a prototype object. This prototype object has its own properties and methods that the new object can access.

Visualizing the Prototype Chain

Consider an object named Student. It inherits from a Person prototype. The Person prototype inherits from an Object prototype. This forms a chain of inheritance:

Student -> Person -> Object

Benefits of Inheritance

Code Reusability: Inherit common properties and methods instead of repeating them in multiple objects. Maintainability: Changes made to the prototype object automatically apply to all inherited objects. Extensibility: Allows objects to be extended with new functionality without modifying existing code.

Example

const person = {
  name: "John Doe",
  age: 30
};

const student = Object.create(person); // Student inherits from Person student.major = "Computer Science";

console.log(student.name); // Outputs "John Doe" (inherited from Person) console.log(student.major); // Outputs "Computer Science" (added to Student)

Tips for Memorization

Visualize the Royal Family: Think of objects as royal family members with inherited traits. Chain Analogy: Remember the inheritance chain as a series of links connecting objects. Imagine a Tree: Visualize the prototype chain as a family tree, with objects as branches and the root object as the trunk.

What's Next?

Polymorphism and Virtual Methods: Explore how inherited methods can behave differently based on the object they are called from, like a king who can lead an army or a student who can study.

Polymorphism and Virtual Methods


What is Polymorphism?

Polymorphism (Greek for "many forms") is the ability for objects to behave differently depending on their data type or class. Consider a "draw" method that can be applied to different shapes. The method will draw a circle for a Circle object and a square for a Square object.

How Virtual Methods Work

Virtual methods are a key component of polymorphism. They allow objects to override or implement methods from their parent class. This means that objects of different classes can have different implementations of the same method.

Visualizing Polymorphism

Imagine a family of animals: a Dog, a Cat, and a Bird. Each animal has a "speak" method, but each method produces a different sound.

Animal "speak" Method Output
Dog bark() "Woof!"
Cat meow() "Meow!"
Bird chirp() "Chirp!"

Tips for Memorization

  • Real-World Analogies: Use examples from real life, like the animal family example above.
  • Tables and Diagrams: Create tables or diagrams that illustrate how different objects respond to the same method.
  • Code Examples: Provide concrete code examples that demonstrate polymorphism in action.

Benefits of Polymorphism

  • Code Reusability: Allows for the creation of generic methods that can be used with different objects.
  • Extensibility: Makes it easy to add new objects or modify existing ones without breaking the code.
  • Flexibility: Enables objects to respond differently to the same method, providing flexibility and customization.
Share Button