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)