In JavaScript, there are several types of objects, each serving a specific purpose. These object types can be categorized based on their characteristics and usage. Easy Coding School are some of the main types of JavaScript objects:
1. Built-in Objects
These are objects provided by the JavaScript language itself.
Object: The base object type from which all other objects inherit.
const person = {
firstName: "John",
lastName: "Doe",
age: 30
};
const numbers = [1, 2, 3, 4, 5];
function greet(name) {
console.log(`Hello, ${name}!`);
}
Date: Used for working with dates and times.
const currentDate = new Date();
const pattern = /hello/i; // Case-insensitive pattern
const result = Math.sqrt(25);
JSON: Used for working with JSON (JavaScript Object Notation) data.
const jsonData = '{"name": "Alice", "age": 25}';
const parsedData = JSON.parse(jsonData);
2. Global Objects:
Objects that are accessible globally in a web browser environment.
Window: Represents the browser window or global context.
// Accessing properties of the window object
console.log(window.innerWidth); // Inner width of the browser window
console.log(window.innerHeight); // Inner height of the browser window
console.log(window.location.href); // URL of the current page
console.log(window.document.title); // Title of the current document
console.log(window.navigator.userAgent); // User agent string
// Using methods of the window object
window.alert("This is an alert!"); // Display an alert dialog
window.confirm("Are you sure?"); // Display a confirmation dialog
const userInput = window.prompt("Enter something:"); // Display a prompt and get user input
Document: Represents the DOM (Document Object Model) of an HTML document.
<!DOCTYPE html>
<html>
<head>
<title>Document Object Example</title>
</head>
<body>
<h1>Hello, Document Object!</h1>
<p>This is an example of using the document object.</p>
<button id="myButton">Click Me</button>
<script>
// Accessing and modifying elements
const heading = document.querySelector('h1');
heading.textContent = 'Hello, Updated Document Object!';
const paragraph = document.querySelector('p');
paragraph.style.color = 'blue';
// Handling events const button = document.getElementById('myButton');
button.addEventListener('click', function() {
alert('Button clicked!');
});
</script>
</body>
</html>
Also read more topic in, How many types of JavaScript arrays.
3. DOM Objects
Objects that represent elements in the Document Object Model (DOM) of a web page.
<!DOCTYPE html>
<html>
<head>
<title>Document Object Example</title>
</head>
<body>
<h1>Hello, Document Object!</h1>
<p>This is an example of using the document object.</p>
<button id="myButton">Click Me</button>
<script>
// Accessing and modifying elements
const heading = document.querySelector('h1');
heading.textContent = 'Hello, Updated Document Object!';
const paragraph = document.querySelector('p');
paragraph.style.color = 'blue';
// Handling events
const button = document.getElementById('myButton');
button.addEventListener('click', function() {
alert('Button clicked!');
});
</script>
</body>
</html>
4. Constructor Objects:
These objects are used to create instances of specific types.
String: Used for working with strings.
const greeting = "Hello, world!";
Number: Used for working with numeric values.
const age = 30;
Boolean: Used for working with true/false values.
const isStudent = true;
5. Prototype Objects
These objects are used as prototypes for inheritance.
Prototype objects are a crucial concept in JavaScript’s object-oriented programming model. Every object in JavaScript is associated with a prototype object that provides properties and methods that can be accessed by the object. Here’s an example to illustrate prototype objects:
// Constructor function for creating person objects
function Person(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
// Adding a method to the prototype of the Person constructor
Person.prototype.getFullName = function() {
return this.firstName + ' ' + this.lastName;
};// Creating person instances using the constructor
const person1 = new Person('John', 'Doe');
const person2 = new Person('Alice', 'Smith');console.log(person1.getFullName()); // Output: "John Doe"
console.log(person2.getFullName()); // Output: "Alice Smith"
6. ES6+ Objects:
With ECMAScript 6 (ES6) and later versions, additional object types were introduced.
Map: A data structure that holds key-value pairs and allows any data type as a key.
const myMap = new Map();
myMap.set("key1", "value1");
Set: A collection of unique values.
const mySet = new Set();
mySet.add(1);
mySet.add(2);
Symbol: A unique and immutable primitive data type, often used as an object property key.
const uniqueKey = Symbol("myKey");
Proxy: Used to define custom behavior for fundamental operations on objects.
const handler = {
get: function(target, property) {
return `Getting property ${property}`;
}
};
const proxy = new Proxy({}, handler);
7. Reflect
Provides methods for intercepting JavaScript operations.
User-Defined Objects: User-defined objects in JavaScript are objects that you define yourself to model specific entities or concepts in your application. You can create user-defined objects using constructor functions or ES6 classes. Here’s an example using both approaches:
Using Constructor Functions:
// Constructor function for creating a Car object
function Car(make, model, year) {
this.make = make;
this.model = model;
this.year = year;
this.isRunning = false;
}
// Adding a method to the Car prototype
Car.prototype.start = function() {
this.isRunning = true;
};
// Creating Car instances
const car1 = new Car("Toyota", "Camry", 2022);
const car2 = new Car("Honda", "Civic", 2023);
// Using the start method
car1.start();
console.log(car1.isRunning); // Output: true
console.log(car2.isRunning); // Output: false
Using ES6 Classes:
class Dog {
constructor(name, breed) {
this.name = name;
this.breed = breed;
this.isBarking = false;
}
bark() {
this.isBarking = true;
console.log(`${this.name} is barking!`);
}
}
// Creating Dog instances
const dog1 = new Dog("Buddy", "Golden Retriever");
const dog2 = new Dog("Luna", "Labrador");
// Using the bark method
dog1.bark(); // Output: "Buddy is barking!"
console.log(dog1.isBarking); // Output: true
console.log(dog2.isBarking); // Output: false
In both examples:
- We define a constructor function or an ES6 class to create instances of user-defined objects (Car and Dog).
- We add properties and methods to the constructor function’s prototype (or directly within the class definition).
- We create instances of the objects using the new keyword, passing necessary parameters to the constructor.
- We use methods and access properties of the instances to model behavior and store data associated with the objects.
User-defined objects allow you to encapsulate data and behavior related to specific entities in your application. They are central to object-oriented programming and enable you to create more organized and maintainable code by grouping related functionalities together.
Custom Constructor Objects: Custom constructor objects are a way to define and create objects in JavaScript using constructor functions. Constructor functions act as blueprints for creating multiple objects with similar properties and methods. Here’s an example of creating custom constructor objects:
// Custom constructor function for creating Person objects
function Person(firstName, lastName, age) {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
}
// Adding a method to the prototype of the constructor
Person.prototype.getFullName = function() {
return `${this.firstName} ${this.lastName}`;
};
// Creating instances using the constructor
const person1 = new Person("John", "Doe", 30);
const person2 = new Person("Alice", "Smith", 25);
// Accessing properties and using the method
console.log(person1.firstName); // Output: "John"
console.log(person2.lastName); // Output: "Smith"
console.log(person1.getFullName()); // Output: "John Doe"
console.log(person2.age); // Output: 25
In this example:
- We define a custom constructor function Person that takes firstName, lastName, and age as parameters and assigns them as properties to the created object (this).
- We add a method getFullName to the prototype of the Person constructor. This method can be accessed by all instances created using the Person constructor.
- We create instances person1 and person2 using the Person constructor.
- We access properties and use the method on these instances to model behavior and store data associated with the objects.
Wrapper Objects: Wrapper objects in JavaScript are used to represent primitive data types (like numbers, strings, and booleans) as objects. This allows you to access properties and methods that are available on objects. JavaScript creates wrapper objects automatically when you attempt to access properties or methods on primitive values.
Here’s an example demonstrating how wrapper objects work:
// Using a wrapper object for a string
const myString = "Hello, world!";
console.log(myString.length); // Output: 13
// Using a wrapper object for a number
const myNumber = 42;
console.log(myNumber.toString()); // Output: "42"
// Using a wrapper object for a boolean
const myBoolean = true;
console.log(myBoolean.valueOf()); // Output: true
In this example:\
- When you access the length property of myString, JavaScript implicitly creates a wrapper object for the string and then accesses the property.
- When you call the toString method on myNumber, JavaScript creates a wrapper object for the number and then calls the method.
- When you call the valueOf method on myBoolean, JavaScript creates a wrapper object for the boolean and then calls the method.
It’s important to note that these wrapper objects are temporary and are automatically created and destroyed as needed. They exist only for the duration of the property access or method call and are not stored in memory.
While wrapper objects can be convenient in some cases, they can also introduce performance overhead due to the additional object creation and destruction. In most situations, you can work directly with primitive values without using wrapper objects, unless you specifically need to access object-related properties or methods.
Each of these object types has its own set of methods and properties, and they serve different purposes in JavaScript programming. Understanding these object types and how to use them effectively is essential for building complex and robust applications.
You can also discover a lot about Javascript by exploring different topics.
Note: We welcome your feedback at Easy coding School. Please don’t hesitate to share your suggestions or any issues you might have with the article!