Object inheritance is one of the most confusing and intimidating things to learn about javascript. That's why today, I want to learn out loud about this subject, so that I can both share and consolidate what I'm learning at the same time.

If you're learning javascript, you may have heard the following phrase a few times.

In javascript: everything is an object

And that is largely true. The primitive datatypes Number, String, Boolean, Undefined and Null are not objects, but other than that, everything is an object. And that is important if you want to understand how object-oriented programming works in javascript.

Object-oriented programming (OOP) allows programmers to store data, structure code and keep code clean, DRY and organized. For one, this means that you keep the data and the functions that work on that data in the same object.

Take, for example, a person for whom you want to calculate his BMI:

var mark = {
  fullName: 'Mark Bell',
  mass: 89,
  height: 1.9,
  calcBMI: function() {
    this.bmi = this.mass/(this.height**2)
    return this.bmi

This looks pretty neat. But even if you do this; and keep your data and the functions that apply to it neatly in the same object, you will still repeat yourself (write duplicate code) often. For example, if you wanted to create multiple objects for multiple people for whom you want to calculate their BMI.

Javascript offers a solution for this, namely something of a blueprint, from which you can generate as many similar objects as you want. In other languages, such a blueprint is often called a class, but in javascript, we call it a constructor or prototype.

So in this case, using the constructor function could look like this:

var Person = function(fullName, mass, height){
  this.fullName = fullName;
  this.mass = mass;
  this.height = height;

The same mark object as before could now be created as follows:

var mark = new Person('Mark Bell', 89, 1.9);

An object constructed from such a prototype/constructor blueprint is called an instance. And the process through which one object gets access to another object's properties and methods is called inheritance.

Talking about methods, we were still missing the method that the mark object already had to calculate his BMI.

Any methods that an instance is supposed to inherit from the constructor can be added using the prototype property of the constructor object:

Person.prototype.calcBMI = function() {
    this.bmi = this.mass/(this.height**2)
    return this.bmi

This will allow every instance of the constructor object to utilize this method.

mark.calcBMI() //24.65

So, in conclusion: javascript is a prototype-based language, where everything that isn't a primitive is an object. And every object in javascript has a prototype property which makes inheritance possible.

I hope this was as enlightening to you as it was to me.

I learned this through the complete javascript course by Jonas Schmedtmann. I highly recommend checking it out.