- JS Introduction
- JS Introduction
- JS Comments
- JS Variables
- JS Datatypes
- JS Operators
- JS Type Conversions
- JS Control Flow
- JS Comparisons
- JS If else
- JS If else Ladder
- JS Ternary Operator
- JS Switch
- JS For Loop
- JS For In
- JS For Of
- JS While
- JS Do While
- JS Break & Continue
- JS Functions
- JS Function Declaration
- JS Function Parameters
- JS Return Statement
- JS Function Expressions
- JS Anonymous Functions
- JS Objects
- JS Objects
- JS Object Methods
- JS Object Constructors
- JS Object Destructuring
- JS Object Prototypes
- JS Map, Filter & Reduce
- JS ES6
- JS ES6
- JS let and const
- JS Arrow Functions
- JS Template Literals
- Destructuring Assignment
- JS Spread Operator
- JS Default Parameters
- JS Classes
- JS Inheritance
- JS Map
- JS Set
- JS Async
- JS Callbacks
- JS Asynchronous
- JS Promises
- JS Async/Await
- JS HTML DOM/BOM
- JS Document Object
- JS getElementbyId
- getElementsByClassName
- JS getElementsByName
- getElementsByTagName
- JS innerHTML
- JS outerHTML
- JS Window Object
- JS History Object
- JS Navigator Object
- JS Screen Object
JavaScript Objects
- Objects in JavaScript are the building blocks of the language. They act as containers for named values, known as properties, and functions, known as methods.
- Think of an object as a real-world entity. For example, a "User" isn't just a string or a number; a user has a name, an email address, an age, and the ability to "log in."
- Properties and methods are accessed using dot notation (
object.property) or bracket notation (object['property']).
Syntax:
// Object Literal Syntax
const person = {
firstName: 'John',
lastName: 'Doe',
age: 30,
greet: function() {
console.log('Hello!');
}
};
- firstName, lastName, age: These are keys (or properties) that hold data values.
- greet: This is a method. It represents an action the object can perform.
const to declare objects. While the properties inside the object can change, using const prevents you from accidentally reassigning the entire object variable to a different value.
Why it is Used:
- Data Organization: Instead of having dozens of standalone variables like
userName,userEmail, anduserAge, you can group them into a singleuserobject. - Code Reusability: Methods allow you to keep functionality right next to the data it operates on, making your code modular and easier to debug.
- Real-world Representation: Objects allow you to model complex systems, such as items in a shopping cart, players in a game, or data fetched from a database API.
Accessing Properties and Methods:
There are two primary ways to get data out of an object. Dot notation is the most common, but bracket notation is essential when your property name is stored in a variable.
// Accessing Properties and Calling a Method
console.log(person.firstName); // Output: John (Dot Notation)
console.log(person['lastName']); // Output: Doe (Bracket Notation)
person.greet(); // Output: Hello!
() when calling a method. If you write person.greet without the parens, JavaScript returns the function definition itself rather than executing the code inside it.
Adding and Modifying Properties:
JavaScript objects are dynamic. You can add new properties or change existing ones at any time during the execution of your program.
// Adding a New Property
person.gender = 'Male';
person['hobby'] = 'Coding'; // You can also use brackets to add properties
// Modifying an Existing Property
person.age = 31;
Object Methods:
Methods often need to access other properties within the same object. To do this, we use the this keyword, which refers to the "owner" of the function (the object itself).
// Method to Display Full Name using 'this'
person.fullName = function() {
return this.firstName + ' ' + this.lastName;
};
console.log(person.fullName()); // Output: John Doe
=>) for object methods if you need to use this. Arrow functions do not bind their own this context, which often leads to undefined errors when trying to access object properties.
Object Constructor:
If you need to create multiple objects of the same "type" (like 100 different cars), writing them all out as literals is inefficient. Constructors act as blueprints.
// Object Constructor Function (Blueprint)
function Car(make, model, year) {
this.make = make;
this.model = model;
this.year = year;
this.getInfo = function() {
return this.year + ' ' + this.make + ' ' + this.model;
};
}
// Creating Instances of the Car Object
const car1 = new Car('Toyota', 'Camry', 2022);
const car2 = new Car('Honda', 'Accord', 2021);
console.log(car1.getInfo()); // Output: 2022 Toyota Camry
Object Destructuring:
Destructuring is a modern (ES6+) syntax that allows you to "unpack" properties from objects into distinct variables quickly. This is heavily used in frameworks like React.
// Object Destructuring
const { firstName, lastName, age } = person;
// Now you can use the variables directly
console.log(firstName, lastName, age); // Output: John Doe 31
console.log(person.firstName) multiple times, you extract it once and use the shorter variable name.
Summary
- Key-Value Pairs: Objects store data in pairs, making data retrieval intuitive.
- Encapsulation: They group related data (properties) and logic (methods) together.
- Flexibility: You can use Dot notation for readability or Bracket notation for dynamic property access.
- Dynamic Nature: Properties can be added, modified, or deleted on the fly.
- Context: Use the
thiskeyword inside methods to refer to the object's own properties. - Scalability: Use Constructors or Classes to create multiple instances of similar objects.