Arrays
Object Literals
An object literal is a way to define an object in JavaScript using a simple, literal notation.
const JsUser = {
name: "Hitesh",
"full name": "Hitesh Choudhary",
age: 18,
location: "Jaipur",
email: "hitesh@google.com",
isLoggedIn: false,
lastLoginDays: ["Monday", "Saturday"]
};
Object literals are a simple and efficient way to create objects with key-value pairs.
Using Symbols as Keys
Symbols are a unique and immutable data type that can be used as keys in objects. This ensures that the key is always unique, avoiding any key collisions.
const mySym = Symbol("key1");
const JsUser = {
name: "Hitesh",
[mySym]: "mykey1",
age: 18,
location: "Jaipur",
email: "hitesh@google.com",
};
Using [mySym]
as a key ensures that it is unique, even if there are other keys with the same name.
Accessing and Modifying Object Properties
Object properties can be accessed and modified using either dot notation or bracket notation.
console.log(JsUser.email); // Access using dot notation
console.log(JsUser["email"]); // Access using bracket notation
console.log(JsUser["full name"]); // Accessing a property with spaces using bracket notation
console.log(JsUser[mySym]); // Accessing a property defined with a Symbol
You can change object properties directly by reassigning them. However, if an object is frozen using Object.freeze()
, its properties cannot be modified.
Adding Methods to Objects
You can add methods to objects, which are functions that operate on the object's properties.
JsUser.greeting = function() {
console.log("Hello JS user");
};
JsUser.greetingTwo = function() {
console.log(`Hello JS user, ${this.name}`);
};
console.log(JsUser.greeting()); // Outputs: "Hello JS user"
console.log(JsUser.greetingTwo()); // Outputs: "Hello JS user, Hitesh"
The greeting
method simply logs a greeting message, while greetingTwo
uses the this
keyword to access the object's name
property dynamically.
Freezing an Object
The Object.freeze()
method can be used to prevent any modifications to an object. Once frozen, properties cannot be added, removed, or changed.
Object.freeze(JsUser);
JsUser.email = "hitesh@microsoft.com"; // This will not change the email
console.log(JsUser.email); // Outputs: "hitesh@google.com"
Even though the email is reassigned after freezing, the change will not be applied.