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.
- 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.
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);
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
};
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:
- Dot Notation:
console.log(jsUser.email); // Output: ayushyadav@gmail.com
- Bracket Notation:
console.log(jsUser["email"]); // Output: ayushyadav@gmail.com
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
Symbols also require bracket notation for access:
console.log(jsUser[mySym]); // Output: myKey1 π
5. Modifying and Freezing Objects π§
Objects in JavaScript are mutable, meaning you can easily change their properties:
jsUser.email = "ayushyadav@google.com";
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
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
};
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 π
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)