-
Hajipur, Bihar, 844101
Hajipur, Bihar, 844101
JS Basics
JS Variables & Operators
JS Data Types & Conversion
JS Numbers & Math
JS Strings
JS Dates
JS Arrays
JS Control Flow
JS Loops & Iteration
JS Functions
JS Functions
Function Definitions
Function Parameters
Function Invocation
Function Call
Function Apply
Function Bind
Function Closures
JS Arrow Function
JS Objects
JS Objects
JS Object Properties
JS Object Methods
JS Object Display
JS Object Constructors
Object Definitions
Object Get / Set
Object Prototypes
Object Protection
JS Classes & Modules
JS Async Programming
JS Advanced
JS Destructuring
JS Bitwise
JS RegExp
JS Precedence
JS Errors
JS Scope
JS Hoisting
JS Strict Mode
JS this Keyword
JS HTML DOM
DOM Intro
DOM Methods
DOM Document
DOM Elements
DOM HTML
DOM Forms
DOM CSS
DOM Animations
DOM Events
DOM Event Listener
DOM Navigation
DOM Nodes
DOM Collections
DOM Node Lists
JS BOM (Browser Object Model)
JS Web APIs
Web API Intro
Web Validation API
Web History API
Web Storage API
Web Worker API
Web Fetch API
Web Geolocation API
JS AJAX
AJAX Intro
AJAX XMLHttp
AJAX Request
AJAX Response
AJAX XML File
AJAX PHP
AJAX ASP
AJAX Database
AJAX Applications
AJAX Examples
JS JSON
JSON Intro
JSON Syntax
JSON vs XML
JSON Data Types
JSON Parse
JSON Stringify
JSON Objects
JSON Arrays
JSON Server
JSON PHP
JSON HTML
JSON JSONP
JS Graphics & Charts
Objects are a fundamental data type in JavaScript used to store collections of key–value pairs. They can represent real-world entities like users, products, students, or settings. Understanding how to define objects correctly is essential because objects are used extensively in web development, APIs, and modern frameworks.
There are several ways to define objects in JavaScript, each with its own use cases, advantages, and trade-offs. Choosing the right method improves code readability, performance, and maintainability.
The simplest and most common way to define an object is using an object literal.
const person = {
firstName: "John",
lastName: "Doe",
age: 25
};
Curly braces {}
enclose key–value pairs.
Keys (also called properties) can be strings or symbols.
Values can be primitives, arrays, functions, or even nested objects.
console.log(person.firstName); // John
console.log(person["age"]); // 25
Tip: Use dot notation for simplicity. Use bracket notation when keys have spaces or are dynamic.
Example: Dynamic Key Access
const key = "lastName";
console.log(person[key]); // Doe
Objects can also be created using constructor functions, which are like blueprints for creating multiple similar objects.
function Person(firstName, lastName, age) {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
}
const person1 = new Person("Alice", "Smith", 30);
const person2 = new Person("Bob", "Brown", 22);
Each new
call creates a separate instance.
Constructor functions allow dynamic object creation with different values.
Methods can be defined inside constructors:
function Person(firstName, lastName, age) {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
this.fullName = function() {
return this.firstName + " " + this.lastName;
};
}
console.log(person1.fullName()); // Alice Smith
Note: Methods inside constructors are copied to each object, which can increase memory usage.
To save memory, you can add methods to the constructor's prototype, so all instances share the same method.
Person.prototype.fullName = function() {
return this.firstName + " " + this.lastName;
};
Shared methods reduce memory usage for multiple instances.
Prototype methods are a key feature of JavaScript OOP.
Object.create()
Object.create()
creates a new object using an existing object as its prototype:
const proto = {
greet() {
return `Hello, ${this.name}`;
}
};
const person = Object.create(proto);
person.name = "John";
console.log(person.greet()); // Hello, John
Supports prototype-based inheritance.
Useful when you want to reuse a prototype object across multiple instances.
Object.defineProperty()
Object.defineProperty()
allows precise control over property attributes:
const person = {};
Object.defineProperty(person, "name", {
value: "John",
writable: true,
enumerable: true,
configurable: true
});
writable
: Can the property value change?
enumerable
: Will it appear in loops?
configurable
: Can the property be deleted or reconfigured?
Tip: This method is useful for creating read-only or hidden properties.
Object.defineProperties()
For multiple properties at once:
Object.defineProperties(person, {
firstName: { value: "Alice", writable: true },
lastName: { value: "Smith", writable: true },
age: { value: 30, writable: true }
});
Ideal for creating complex objects with many controlled properties.
Objects can contain other objects, allowing hierarchical structures:
const student = {
name: "Alice",
marks: {
math: 90,
science: 85
}
};
console.log(student.marks.math); // 90
Nested objects represent real-world data structures, such as a user with address and contact info.
Access them using dot notation or bracket notation.
You can add properties after object creation:
const car = {};
car.brand = "Toyota";
car.model = "Camry";
car.year = 2025;
Useful when properties are not known in advance.
Bracket notation allows dynamic keys:
const key = "color";
car[key] = "Red";
Object literals are best for simple, static objects.
Constructors are ideal for creating multiple instances with the same structure.
Object.create() is best for prototype-based inheritance.
DefineProperty/defineProperties is ideal for precise property control.
Plan nested objects carefully for real-world applications.
Consistency in object definition improves readability, debugging, and maintenance.
JavaScript objects can be defined using:
Object literals (simple, static objects)
Constructor functions (blueprints for multiple instances)
Object.create() (prototype-based inheritance)
Object.defineProperty()/defineProperties() (control over property attributes)
Objects can contain nested objects or arrays.
Dynamic property assignment allows flexibility.
Choosing the right definition method ensures efficient, maintainable code.
Objects are foundational to all JavaScript programming, from simple scripts to complex applications, and mastering their definitions is crucial for effective coding.
Object Literal Creation
Create an object person
using object literal syntax with firstName
, lastName
, and age
. Log all properties using dot notation and bracket notation.
Dynamic Property Addition
Create an empty object car
and dynamically add brand
, model
, and year
properties. Log the final object.
Constructor Function
Define a constructor Person
with firstName
, lastName
, and age
. Create two objects and log their details.
Prototype Method
Add a fullName()
method to the Person
prototype and demonstrate that both instances can use it.
Object.create() Usage
Create a prototype object with a greet()
method. Then use Object.create()
to define a new object that inherits this method. Call greet()
on the new object.
Object.defineProperty()
Create an empty object student
and define a property name
using Object.defineProperty()
. Set it as read-only. Try to change it and log the result.
Object.defineProperties()
Define an object student
with multiple properties (firstName
, lastName
, age
) using Object.defineProperties()
. Log all properties.
Nested Object Definition
Create a student
object with nested marks
object containing math
and science
. Log the nested values using dot notation.
Dynamic Key Access
Create an object with a property whose key is stored in a variable. Access and log this property dynamically.
Comparing Definition Methods
Create two objects representing a book
, one using object literal and one using a constructor. Log both objects and discuss the differences in structure and flexibility.
JS Basics
JS Variables & Operators
JS Data Types & Conversion
JS Numbers & Math
JS Strings
JS Dates
JS Arrays
JS Control Flow
JS Loops & Iteration
JS Functions
JS Functions
Function Definitions
Function Parameters
Function Invocation
Function Call
Function Apply
Function Bind
Function Closures
JS Arrow Function
JS Objects
JS Objects
JS Object Properties
JS Object Methods
JS Object Display
JS Object Constructors
Object Definitions
Object Get / Set
Object Prototypes
Object Protection
JS Classes & Modules
JS Async Programming
JS Advanced
JS Destructuring
JS Bitwise
JS RegExp
JS Precedence
JS Errors
JS Scope
JS Hoisting
JS Strict Mode
JS this Keyword
JS HTML DOM
DOM Intro
DOM Methods
DOM Document
DOM Elements
DOM HTML
DOM Forms
DOM CSS
DOM Animations
DOM Events
DOM Event Listener
DOM Navigation
DOM Nodes
DOM Collections
DOM Node Lists
JS BOM (Browser Object Model)
JS Web APIs
Web API Intro
Web Validation API
Web History API
Web Storage API
Web Worker API
Web Fetch API
Web Geolocation API
JS AJAX
AJAX Intro
AJAX XMLHttp
AJAX Request
AJAX Response
AJAX XML File
AJAX PHP
AJAX ASP
AJAX Database
AJAX Applications
AJAX Examples
JS JSON
JSON Intro
JSON Syntax
JSON vs XML
JSON Data Types
JSON Parse
JSON Stringify
JSON Objects
JSON Arrays
JSON Server
JSON PHP
JSON HTML
JSON JSONP
JS Graphics & Charts