𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 𝗢𝗯𝗷𝗲𝗰𝘁𝘀: 𝗕𝗮𝘀𝗶𝗰𝘀 𝘁𝗼 𝗖𝗥𝗨𝗗
JavaScript objects group related data and functions together. Instead of using separate variables, you use key-value pairs.
Think of an entity like a student. An object represents this entity in your code.
Every object has three parts:
- Entity: The thing itself (e.g., a Student).
- State: What the object has (e.g., name, age). These are properties.
- Behavior: What the object does (e.g., study). These are methods.
How to create objects:
Object Literal This is the most common way. You use curly braces to define the object directly. It is short and easy to read. let student = { name: "Saravanan", age: 25 };
Object Constructor You use the new keyword to build an object. let student = new Object(); student.name = "Saravanan";
Most developers prefer the literal method.
CRUD Operations:
You perform four basic tasks with object data:
- Create: Define a new object.
- Read: Access data using dot notation (person.name) or bracket notation (person["name"]).
- Update: Change an existing value (person.age = 26).
- Delete: Remove a property using the delete keyword (delete person.age).
Advanced Concepts:
- Methods: A function inside an object is a method. You can use shorthand syntax to write them.
- Nested Objects: An object can hold another object inside it. This helps you organize complex data like an address.
- Data Types: Objects can store strings, numbers, booleans, arrays, functions, and other objects.
Summary of an object structure:
- name: String
- age: Number
- address: Nested Object
- greet: Method (Function)
Source: https://dev.to/dev_saravanan_journey/javascript-objects-from-basics-to-crud-operations-46bg