An object is a dynamic data structure that stores related data as key-value pairs, where each key uniquely identifies its value.
- The values of properties can be primitives, objects, or functions (known as methods when defined inside an object).
- Objects are mutable and dynamic properties can be added, modified, or deleted at any time.
- Objects allow data grouping and encapsulation, making it easier to manage related information and behaviour together.
Object Literal
An object literal "literally" describes an object using a concise syntax with zero or more key:value pairs inside curly braces to describe all the object properties:
{ firstName:"John",
lastName:"Doe",
age:50,
eyeColor:"blue"}
Note : You should declare objects with the const keyword.
There are two primary ways to create an object in JavaScript:
1.Creation Using Object Literal
The object literal syntax allows you to define and initialize an object with curly braces {}, setting properties as key-value pairs.
let obj = {
name: "vidhya",
age: 23,
job: "Developer"
};
console.log(obj);
2.Creation Using new Object() Constructor
let obj = new Object();
obj.name= "Alex",
obj.age= 4,
obj.job= "WatchMan"
console.log(obj);
Basic Operations on JavaScript Objects
- Accessing Object Properties
You can access an object’s properties using either dot notation or bracket notation
// Using Dot Notation
console.log(obj.name);
// Using Bracket Notation
console.log(obj["age"]);
- Modifying Object Properties
Properties in an object can be modified by reassigning their values.
let obj = { name: "vidhya", age: 23 };
console.log(obj);
obj.age = 25;
console.log(obj);
- Adding Properties to an Object
You can dynamically add new properties to an object using dot or bracket notation
- Removing Properties from an Object
The delete operator removes properties from an object.
- Checking if a Property Exists
You can check if an object has a property using the in operator or hasOwnProperty() method.
- Iterating Through Object Properties
Use for...in loop to iterate through the properties of an object.
- Merging Objects
Objects can be merged using Object.assign() or the spread syntax { ...obj1, ...obj2 }.
- Object Length
You can find the number of properties in an object using Object.keys().
Reference :







Top comments (0)