JAVASCRIPT

Objects


JavaScript is often referred to as an "object-based" language rather than a purely object-oriented language like Java or C++. This distinction arises from JavaScript's unique approach to handling objects and its flexible nature.


An object is a fundamental data type that represents a collection of key-value pairs. It allows to store and organize data in a structured way.

 

Creating An Object:

 

1. Using Object Literals:

It is the simplest way to create an object just by using object literal notation `{}`.
 

// object notation-{}
let person = {
    name: "Wasif",
    age: 23,
    city: "India"
};

 

2. Using object Constructor:

We can create an object through the object constructor.

 

// object constructor
let person = new Object();
person.name = "Wasif";
person.age = 23;
person.city = "India";

 

3. Using function Constructor:

We also create a object by using function Constructor.
 

// function constructor
function Person(name, age, city) {
    this.name = name;
    this.age = age;
    this.city = city;
}

let person1 = new Person("Wasif", 23, "India");
let person2 = new Person("Rohit", 25, "German");

 

4. Using ES6 Classes:

Now JavaScript also supports class bases syntax for creating object.
 

// ES6 classes
class Person {
    constructor(name, age, city) {
        this.name = name;
        this.age = age;
        this.city = city;
    }
}

let person1 = new Person("Wasif", 23, "India");
let person2 = new Person("Rohit", 25, "German");

 

Advantages of Object in JavaScript:

 

Encapsulation:

Objects encapsulate both data and behavior (methods) into a single entity. This means you can organize related data and functions together, which enhances code readability and maintainability.

 

Abstraction:

Objects provide a way to abstract complex systems into simpler, higher-level representations. This allows you to focus on the essential characteristics of an entity while hiding unnecessary details.

 

Modularity:

Objects promote modularity by enabling you to break down your code into smaller, self-contained units. Each object can represent a module or component of your system, with its own set of properties and methods. This modular approach facilitates code reuse and makes it easier to maintain and extend your codebase.

 

Inheritance:

JavaScript supports prototypal inheritance, where objects can inherit properties and methods from other objects (prototypes). This allows you to create hierarchies of objects, with child objects inheriting behavior from parent objects.