JavaScript Object and Object Prototypes: What are they?🤷‍♂️🤔
Tags: webdev, javascript, beginners, tutorial
Published: 2023-08-20 18:14:25

You might have come across this concept of Object prototypes when learning JavaScript, and just like any other coding concept, it might be intimidating at first and challenging to grasp. But hey, as a fellow JavaScript developer, I can relate and understand that.
So, in this article, I will try to break this concept into pieces that are as easy to grab and digest. And with that let's dive right in.

**What are Objects?**
An object in JavaScript is like a virtual "box" or "container" that holds various things, known as properties. These properties can be values, like numbers, text, or even functions that do something specific.

Why don't we use an analogy to better understand this?
Think of a JavaScript object like a person's profile on a social media platform. The profile might contain various details:

- Name: The person's name, such as "John Doe."
- Age: The person's age, like 30.
- Likes to play soccer: A statement that might be true or false.
 
Translated in JavaScript that would be:

```javascript
var profile = {
  name: "John Doe",
  age: 30,
  likesSoccer: true
};

```

How can we access the object's information you ask?
Well, for doing that there are two methods:

**Method 1**
We can use the `.` (dot), let's access the profile object to get the age and then store it in a variable;

```javascript
var johnsAge = profile.age;
```
**Method 2**
The other way of doing this is using the `[]` (square brackets), let's do the same;

```javascript
var johnsAge = profile['age'];
```
So in conclusion we can say that a JavaScript object is a collection of information, like a person's profile, where you can store and organize various details. It makes handling related data more manageable, and you can quickly access specific information when you need it.

**Case study:**

Let's say you want to make objects for several people like employees in a company. Making a single object at a time can be very tedious. So how can we cut the task?

**Using a regular function to make an object:**

So, one way of making several objects without having to hardcode them is using a regular function. Let's take an example of employees in a company, whereby, each employee has a name, age and salary.

In a function, what we will do is that, instead of assigning the values directly, we will pass them as parameters and then pass arguments when we want to make a new object.

```javascript
function createEmployee(name, age, salary) {
  var employee = {
    name: name,
    age: age,
    salary: salary
  };
  return employee;
}

```
Now let's use the function to create two employees,

```javascript
// Example usage
var employee1 = createEmployee("John Doe", 30, 50000);
console.log(employee1); // Outputs: { name: 'John Doe', age: 30, salary: 50000 }

var employee2 = createEmployee("Jane Doe", 25, 50000);
console.log(employee2); // Outputs: { name: 'Jane Doe', age: 25, salary: 50000 }

```

But, what if I told you there was even a better way of doing this? 
You see, in the above function, we must create an object and return it for it to work, but the JavaScript engine can do that for us.

'How?' You may ask;

**Using a constructor function to make the objects:**

Let's convert the above function to a constructor function.

First of all we do not have to create an object inside the function, so the `var employee = {//employee details}` and the `return employee;` will be eliminated since as I told you the JavaScript engine will do that for us.
Secondly, the parameters will remain. I can hear the question you are asking, 'Since there is no object declared, how will the arguments of the parameter be assigned to the objects we create?' Well, we are headed there.
Let's see  what the constructor function looks like.

```javascript
function Employee(name, age, salary) {
  this.name = name;
  this.age = age;
  this.salary = salary;
}
```
Now let us make objects using the constructor function;

```javascript
// Example usage
var employee1 = new Employee("John Doe", 30, 50000);
console.log(employee1); // Outputs: Employee { name: 'John Doe', age: 30, salary: 50000 }

var employee2 = new Employee("Jane Doe", 25, 50000);
console.log(employee2); // Outputs: Employee { name: 'Jane Doe', age: 25, salary: 50000 }
```
Notice the difference?
The most noticeable difference is the use of the `new` keyword and the `this` keyword in our code. Let's tackle the `new` first. In JavaScript, we use the `new` keyword when calling the constructor function, which creates a new object and invokes the constructor function to initialize its properties (your question answered ). And when using the `this` keyword, we assign the values from the parameters to the properties of the object being created. 

Also, you can note that we have a single word to name our constructor function `Employee()` compared to the usual naming of other functions. Well, though there is no technical reason for this, it is a best practice to use this naming system to ensure that other developers can be able to distinguish between the constructor functions and regular functions.

### So what is the difference?

**Regular Function:**

- **Mechanism:** It explicitly creates an object inside the function, assigns values to its properties, and returns the object.
- **Invocation:** Called like any normal function, without the new keyword.
- **Intention:** Generally used when you want to create an object in a one-off or specific way.
- **Scope:** Any properties or methods defined within the function are confined to that function unless explicitly returned.

**Constructor Function:**

- **Mechanism:** Utilizes the `this` keyword to assign values to the properties of the newly created object that's implicitly created by the new keyword.
- **Invocation:** Called with the new keyword, which creates a new object instance and calls the constructor to initialize it.
- **Intention:** Designed to create multiple instances of objects with the same structure, facilitating code reusability.
- **Prototype Inheritance:** Constructor functions inherently set up a link to the object's prototype, allowing all instances created by the constructor to share methods and properties defined on the prototype. (covered below)

How cool is that function?

Now, let's say all employees should have the ability to introduce themselves. What that means is that we should have a method that should be accessible to every object that we make using the constructor function Employee(). How can we make that happen? You could add a method inside the constructor, but it would be duplicated for every employee object created, wasting memory. Well, introducing:
Well, introducing:

### Prototypes.

**What are object prototypes?**

A prototype in JavaScript is a special object that other objects can access to share properties and methods. It's like a blueprint that objects can reference. The JavaScript engine creates a prototype for every function, it does not matter if it is a constructor or a regular function.

**Why Use Prototypes?**

Prototypes allow you to define properties and methods that are shared across all instances of a particular object. This avoids duplicating the same code for each instance.

Let's see a diagram of how a prototype works:

![prototype](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ola6quydc9j7wu99o5yq.png)
As you can see the indication by the arrows, both employees have access to the prototype, so, we don't have to create a function in the constructor for every instance of employee.

Now in our `Employee()` function, how can we construct that? Here is how:

```javascript
Employee.prototype.introduce = function() {
  return `Hi, I'm ${this.name}, and I earn $${this.salary} per year.`;
};

```
Let's see if Jane and John can introduce themselves;

![prototype](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ef2tk0swb7c88xw8hc5p.png)
Oh yes! They can.
You see, not so hard. How about we create a new employee and see if they can access our prototype?

```javascript
function Employee(name, age, salary) {
    this.name = name;
    this.age = age;
    this.salary = salary;
  }

  var employee1 = new Employee("John Doe", 30, 50000);
  var employee2 = new Employee("Jane Doe", 25, 50000);

  Employee.prototype.introduce = function() {
    return `Hi, I'm ${this.name}, and I earn $${this.salary} per year.`;
  };

  var employee3 = new Employee("Kelvin", 23, 40000);
  console.log(employee3.introduce()); 

```
Run that:

![prototype](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/i2qdbwm0nzss6fexj643.png)

What do you know? Kelvin can as well introduce himself.

Well, thanks for learning with me, this is just a shallow touching of the Object and Object prototypes. For a detailed lesson, check [this](https://youtu.be/fBpPfPjxOhc) out.

Like, comment and share.