DEV Community

Aman Kumar
Aman Kumar

Posted on • Edited on

Mastering JavaScript Objects: From Symbols to Freezing and Beyond! part 1

Objects in JavaScript are one of the most versatile and important structures. They allow you to group related data, like properties and functions, into a single entity. Today, we will explore how to work with objects, from creating them using constructors to object literals, and dive into some handy methods for handling them. Let’s get started! πŸ˜„

1. Objects and Singleton Behavior 🧐

When we create objects in JavaScript, there are two common ways: object literals and constructors. Here's a simple breakdown:

  • Object literals: This is like writing the object directly using curly braces {}. Every time you create a new object this way, it's a separate object, even if they have the same properties. They are not singletons, meaning they're not unique β€” you can create many objects that look the same but are still different.

Example:

  const user1 = { name: "Alice" };
  const user2 = { name: "Alice" };
  // user1 and user2 are separate objects, even though they look the same.
Enter fullscreen mode Exit fullscreen mode
  • Constructor functions: This is like a blueprint for objects. When you use a constructor function, it creates a singleton, meaning the object is unique. Even if you make multiple references to it, they all point to the same object.

Example:

  function User(name) {
    this.name = name;
  }

  const user1 = new User("Alice");
  const user2 = user1;
  // user1 and user2 refer to the same object.
Enter fullscreen mode Exit fullscreen mode

In simple terms:

  • If you use literals, you get a fresh object every time.
  • If you use a constructor, you create a single, unique object that can be shared across different parts of your code.

2. Creating an Object Using Object.create βš™οΈ

The Object.create method allows you to create a new object using an existing object as a prototype. Here's an example:

const newObject = Object.create(existingObject);
Enter fullscreen mode Exit fullscreen mode

This is useful when you want to maintain prototype inheritance. 🧬


3. Object Literals: The Basics πŸ“š

Let's explore object literals with an example:

const mySym = Symbol("key1"); // πŸ”‘ Declaring a Symbol

const jsUser = {
    name: "Ayush",               // πŸ§‘β€πŸ’» Key (as string) and value
    "full name": "Ayush Yadav",  // Keys with spaces must be in quotes
    [mySym]: "myKey1",           // Using symbol as a key
    age: 21,                     // πŸ”’ Number as a value
    location: "Azamgarh",        // 🌍 Location
    email: "ayushyadav@gmail.com", // πŸ“§ Email
    isLoggedIn: false,           // πŸšͺ Login status
    lastLoggedInDays: ["Monday", "Tuesday", "Thursday"]  // πŸ—“οΈ Arrays as values too
};
Enter fullscreen mode Exit fullscreen mode

In the object above, we see different types of values: strings, symbols, numbers, booleans, and even arrays. Notice how symbols are used as keys by placing them inside brackets ([]).


4. Accessing Object Properties πŸ”“

There are multiple ways to access object properties:

  1. Dot Notation:
   console.log(jsUser.email); // Output: ayushyadav@gmail.com
Enter fullscreen mode Exit fullscreen mode
  1. Bracket Notation:
   console.log(jsUser["email"]); // Output: ayushyadav@gmail.com
Enter fullscreen mode Exit fullscreen mode

The bracket notation is especially useful when keys contain spaces, like "full name" (πŸ“›), which cannot be accessed using dot notation:

console.log(jsUser["full name"]); // Output: Ayush Yadav
Enter fullscreen mode Exit fullscreen mode

Symbols also require bracket notation for access:

console.log(jsUser[mySym]); // Output: myKey1 πŸ”‘
Enter fullscreen mode Exit fullscreen mode

5. Modifying and Freezing Objects 🧊

Objects in JavaScript are mutable, meaning you can easily change their properties:

jsUser.email = "ayushyadav@google.com";
Enter fullscreen mode Exit fullscreen mode

However, you can freeze objects to prevent modifications using Object.freeze:

Object.freeze(jsUser);
jsUser.email = "ayushyadav@microsoft.com"; // ❌ This change won't take effect
console.log(jsUser.email); // Output: ayushyadav@google.com
Enter fullscreen mode Exit fullscreen mode

Once frozen, your object becomes read-only! πŸ§Šβ„οΈ


6. Adding Methods to Objects πŸ€–

Objects can also contain functions, often referred to as methods. Let’s add a couple of methods to our jsUser object:

jsUser.greetings = function() {
    console.log("Hi JS user πŸ‘‹");
};

jsUser.greetings2 = function() {
    console.log(`Hi JS user, ${this.name}`);  // 'this' refers to the object
};
Enter fullscreen mode Exit fullscreen mode

Calling these methods will produce the following outputs:

console.log(jsUser.greetings());  // Output: Hi JS user πŸ‘‹
console.log(jsUser.greetings2()); // Output: Hi JS user, Ayush πŸŽ‰
Enter fullscreen mode Exit fullscreen mode

Summary 🎯

JavaScript objects are a powerful way to store and manipulate data. In this blog, we covered:

  • Creating objects using both Object.create and object literals.
  • Accessing object properties via dot and bracket notations πŸ”“.
  • Preventing object modifications with Object.freeze 🧊.
  • Adding functions to objects, turning them into methods πŸ€–.

These basics are a great starting point for mastering JavaScript objects. Try experimenting with different key types, methods, and freezing objects to solidify your understanding! πŸ’‘

Top comments (0)