DEV Community

Cover image for JavaScript Object and Object Prototypes: What are they?🤷‍♂️🤔
Guchu Kelvin
Guchu Kelvin

Posted on

JavaScript Object and Object Prototypes: What are they?🤷‍♂️🤔

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:

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

Enter fullscreen mode Exit fullscreen mode

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;

var johnsAge = profile.age;
Enter fullscreen mode Exit fullscreen mode

Method 2
The other way of doing this is using the [] (square brackets), let's do the same;

var johnsAge = profile['age'];
Enter fullscreen mode Exit fullscreen mode

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.

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

Enter fullscreen mode Exit fullscreen mode

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

// 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 }

Enter fullscreen mode Exit fullscreen mode

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.

function Employee(name, age, salary) {
  this.name = name;
  this.age = age;
  this.salary = salary;
}
Enter fullscreen mode Exit fullscreen mode

Now let us make objects using the constructor function;

// 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 }
Enter fullscreen mode Exit fullscreen mode

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
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:

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

Enter fullscreen mode Exit fullscreen mode

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

prototype
Oh yes! They can.
You see, not so hard. How about we create a new employee and see if they can access our prototype?

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()); 

Enter fullscreen mode Exit fullscreen mode

Run that:

prototype

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 out.

Like, comment and share.

Top comments (0)