An object in JavaScript is a collection of properties, where a property is an association between a name and a value. Objects can be declared in two primary ways: using literals and constructors.
Singleton Objects vs. Object Literals
When objects are created using constructors, they are singletons, meaning they are unique instances. In contrast, when objects are created using literals, multiple instances of that object can be created.
Using Object Literals
Object literals provide a simple and concise way to create objects. Here's an example:
const jsUser = {
name: "harsh",
age: 21,
location: "haryana",
email: "harsh@microsoft.com",
isLoggedIn: false,
lastLoginDays: ["Monday", "Saturday"]
};
//let's see how to access this object
console.log(jsUser.email); //outputs: harsh@microsoft.com
console.log(jsUser["email"]); //outputs: harsh@microsoft.com
//use this method when key value pair is written in the form of
//"email": "harsh@microsoft.com"
How to use symbols in objects
In JavaScript, a Symbol
is a unique and immutable primitive value that can be used as an identifier for object properties.
Let's add a symbol in keys of an object:
const mySym = Symbol("key1");
const jsUser = {
name: "harsh",
age: 21,
location: "haryana",
mySym = "myKey1",
email: "harsh@microsoft.com",
isLoggedIn: false,
lastLoginDays: ["Monday", "Saturday"]
};
console.log(jsUser.mySym); //outputs: myKey1
//but this mySym is still not being used as a symbol, also if we check
//its type, then it will show string
console.log(typeof jsUser.mySym); //outputs: string
Correct way of using it as a symbol inside an object
const mySym = Symbol("key1");
const jsUser = {
name: "harsh",
age: 21,
location: "haryana",
[mySym] = "myKey1",
email: "harsh@microsoft.com",
isLoggedIn: false,
lastLoginDays: ["Monday", "Saturday"]
};
console.log(jsUser[mySym]); //outputs: mykey1
Now have a look at some basic information about objects
- How to change values:
jsUser.email = "harsh@chatgpt.com";
- How to lock values so that anyone can't change them:
Object.freeze(jsUser);
jsUser.email = "harsh@microsoft.com";
console.log(jsUser.email); //outputs: harsh@chatgpt.com
adding function to an object
jsUser.greeting = function(){ console.log("Hello js User") } console.log(jsUser.greeting); //outputs: [Function (anonymous)] // It means function has not been executed, only reference of that function is received console.log(jsUser.greeting()); //outputs: hello js user //undefined
Another example
jsUser.greetingTwo = function(){ console.log(`Hello js User, ${this.name}`); } console.log(jsUser.greetingTwo); //outputs: [Function (anonymous)] console.log(jsUser.greetingTwo()); //outputs: hello js User, harsh //undefined //The this keyword in JavaScript is used to refer to the object from //which the function was called. It provides a way to access properties //and methods of that particular object.