Object-oriented Programming in JavaScript

Amila Devin
11 min readFeb 26, 2022
Object-oriented Programming in JavaScript

What is Object-oriented Programming?

Object Oriented Programming
Object Oriented Programming

Object Oriented Programming is a programming paradigm centered around objects rather than functions.

💥 Object Oriented Programming is not a programming Language or a tool. It is a style of programming or programming paradigm.

Object-oriented Programming Supported Programming Languages

✅ C#

✅ C++

✅ Java

✅ Ruby

✅ Python

✅ JavaScript

💥 There is the popular frameworks out there that you might be using are actually designed with object-oriented programming concepts. ex: Angular

Why Object-oriented Programming ?

There is a programming procedure that divides a program into a function. So we have data stored in a bunch of variables and functions that operate on the data.

Procedural Programming
Procedural Programming

This style of programming is very simple and straightforward. But in this style, programs grow it will end up with a bunch of functions that are all over the place.

bunch of functions
bunch of functions

In that case you make a change to one function and then several other functions break. It’s called spaghetti code. There so much interdependence between all these functions it become problematic. That’s why we using Object-oriented Programming.

In Object-oriented Programming we combine a group of related variables into a unit. that unit is called an object. We refer to these variables as properties and the functions as methods.

methods & properties
methods & properties
Car methods and Properties
Example in Real world

Four Pillars of Object-oriented Programming

  1. Encapsulation : a process of binding the data with the functions which act upon the data. >>Example Code
  2. Abstraction : a way of hiding the implementation details and showing only the functionality to the users. >>Example Code
  3. Inheritance : Inheritance enables you to define a class that takes all the functionality from a parent class and allows you to add more >>Example Code
  4. Polymorphism : a core concept of an object-oriented paradigm that provides a way to perform a single action in different forms.>>Example Code

Setting Up the Development Environment for JavaScript

You can use any code editor as your wish.

♦ notepad, notepad ++

Sublime Text

Visual Studio Code

I’m using Visual Studio code for this. because it has lot of features.

In VS code have extension panel in the left side and you can install live sever extension. That I’m going to use to serve our application.

live server
install the Live Server Extension

Then choose a Location/Folder for to save your project, right click and select open with code (NOTE: This is a only one way to open with vs code)

open with Vs code
open with Vs code

Let’s Create your First JavaScript Program:

Then Make two files name as Index.html and Index.js. Index.html file is a HyperText Markup Language file format used as the basis of a web page. HTML is a file extension used interchangeably with HTM. And Index.js is a JS (JavaScript) are files that contain JavaScript code for execution on web pages. JavaScript files are stored with the .js extension. Inside the HTML document, you can either embed the JavaScript code using the <script></script> tags or include a JS file.

After Creating files, in index.html type start up html tags. then inside the body tag type <script src=”index.js”></script>. This src=”index.js” helps to create a link between html file and JavaScript file. Then inside the index.js file you can type any JavaScript code as you wish. In first step we can print hello World inside the console. for that type this code : console.log(“Hello World”)

Then Open the index.html file using live server or any other method then check your browser console 😃

>>Source Code

live server runnig
Code Running using live server

Objects in JavaScript

JavaScript is all amount objects so in order to learn OOP first we need to good understanding of objects.

We can use let keyword in es6 which is replacement for var so in es5 and before we had var for declaring variables but it has number of issues when it comes to scoping. So, we can use either let or const. With const you’re basically defining a constant. so you won’t be able to reassign it. If you want to reassign a variable use let.

var vs let vs const

Object Literals

To create an object I’m gonna use const to define a constant. So let’s call this circle and to set it to an object.

create an object
create an object

So this curly braces we refer to them as object literal syntax.

An object in JavaScript is essentially a collection of key value pairs. So inside that curly braces we can add a key value pairs.

collection of key value pairs
collection of key value pairs

In this code we have a object what we done earlier. In that object has three members called radius, Location and draw. if a member is a function, we can refer to that as a method. So in our object draw is a method. these other members are what we call properties.

NOTE: Technically in OOP, properties and methods are fundamentally different. Because property is used to hold values. A function or a method is used to define some logic.

So, now that we have this circle object we can access its members using dot notation.

>>Source Code

creating an object

Object Literals issue:

Let’s imagine we want to create another circle with the currant implementation.

nother circle with the currant implementation wrong method
another circle with the currant implementation

This code can be a problem if we have one or more methods in our object. In this case we have duplicated methods called draw();. So if there is a bug in this method and we have to come back and fix it multiple places. Now imagine if the circle object had ten or more methods 😫. So, Object literal syntax is not good way to create an object and duplicate it if this object has at least one method. If object has one or more methods then we can say that object has behavior. In that Case we can use factory or a constructor.

Factory

When a function creates and returns a new object, it is called a factory function. For that we can define a function called createCircle();

>>Source Code

factory function
factory function

Constructor

In a constructor function this does not have a value. It is a substitute for the new object.

So, we can define a function, but the naming convention we use for a constructor function is different. The first letter should be uppercase.

constructor function
constructor function

Further, Our circle function is gonna take a radius parameter. But in the body instead of returning an object we’re gonna use this keyword to set the properties of this object.

NOTE: “this” is basically a reference to the object that is executing this piece of code.

constructor function
constructor function

let we use the new operator, a few things happen under the hood. That new operator will create an empty object. Then it will set this to point to that object. Because by default this point to the global object. I you’re running this code inside of a browser, the global object is the window object. if you’re running it inside a node environment, global object is global.

Let’s check this out 😎 :

In Our code, I add a new line inside the function.

>>Source Code

So, Now you can see this circle object in the console and inside the object we have two members (draw and radius). This is because we use the new operator for call that function.

If new keyword removed:

>>Source Code

So, you can see the output. this reference is the window object. This is the global object in a browser.

🛑 “This is a bad practice.” Because they are available everywhere. So, it is possible that one function or another will modify the value of these variables accidentally and create bug in our application.

So, When we use the “new” operator to call a function three things happens.

  1. new operator will create empty object.
  2. then, it will set this to point to that object .
  3. finally, it will return that object from the constructor function.

NOTE: In this constructor function there are not return statement. because it happen automatically when we use the new operator.

Basically we have to ways to create an object. We can use a factory function or a constructor. They are regular function in JavaScript.

Constructor Property

Every Object in JavaScript has property called constructor. And that references the function that was used to construct or create that object. So, earlier we create two object name as circle and circle2.

Let look at the constructor property:

To do that you should type circle2.constructer and press enter.

So, You can see it return our circle function that we use to create that object 2.

Now type circle.constructer and press enter

This is a also a function. because we can see there is a orange f and as you can see the first letter of that function is uppercase. So, this is a built-in constructor function in JavaScript.

When we create an object using the object literal syntax, internally the JavaScript engine uses that constructor function.

Example:

I define a object like this.

let x = {};

JavaScript engine will translate that to something like this.

let x = new object();

In JavaScript we have a few other built-in constructors.

Example:

new String(); //’’, “”, ``

new Boolean(); // true, false

new Number(); // 1,2,3,…

NOTE: Every object has a constructor property and that references the function that was used to create an object.

Functions are Objects ?

Yes, Functions are objects. Values can be passed to a function, and the function will return a value. In JavaScript, functions are first-class objects, because they can have properties and methods just like any other object. What distinguishes them from other objects is that functions can be called. In brief, they are Function objects.

Example:

lets return the name of the function

Value vs Reference Types

JavaScript we have two categories of types.

  1. Value Types / Primitives : Number, String, Boolean, Symbol, undefine, null
  2. Reference Types : Object, Function, Array

How Primitives and Objects behave differently?

Let’s Define primitives x and y

In console let’s log x and y

they are independent. so when we work with primitives value 10 stored inside the x variable. when we copy that variable that value that is stored in the variable is copied into new variable y.

If we use reference type or an object.

In console let’s log x and y

You can see x and y variable value properties are 20. So, when we use an object the object is not stored in in that variable. That object is stored somewhere else in the memory. And the address of that memory location is stored inside that variable.

NOTE: Primitives are Copied by their value and Objects are copied by their reference

Adding or Removing Properties

Objects in JavaScript are dynamic. That means after you create them you can add extra properties in them or delete some properties.

Adding Properties
Delete Properties

>>Source Code

Enumerating Properties

Sometimes you need to iterate over or enumerate the properties in an object we can do that for in loop

in every iteration key will hold the value of one key in this object

let log that on the console.

So, we can see, we have radius and draw. So, it’s returning both properties and methods.

If you want get the value of these properties you can use bracket notation.

If we want to get only the properties and not the methods.

To get all the keys and an objects.

with approach we cannot separate properties from methods.

If an object has given property for that we use the in operator.

>>Source Code

Abstraction

In OOP we have a concept called abstraction. Abstraction means we should hide the details and complexity and show or expose only the essentials.

Private Properties and Methods

Local variable are inside the function, when we get out of this function. That variable goes out of the scope and dies. With this technique we can easily hide certain members from the outside.

So, defaultLocation implementation detail. We don’t want this to be accessible from the outside. instead of setting it as a property on our new object we can define it as a local variable.

And same token we can covert methods to a private methods (ex: computeOptimumLocation). In that case, we can recalling computeOptimumLocation inside the draw method. So, computeOptimumLocation function is not a method So, we can access it directly inside the draw method. This concept called as Closure.

NOTE: Closure determines what variable will be accessible to an inner function.

Getters and Setters

>>Source Code

setters & Getters in JavaScript

circle.getDefaultLocation(); syntax to call that getter method in line 11.

However, it would be nicer if we could access this property like this:

circle.getDefaultLocation = 0;

But we shouldn’t be able to set this from the outside. we can only read it. So, in line 20 I define a property like that. then inside the console we can see the circle object. there is a new property name as defaultLocation:(…). this is a computed property. When we click (…) this that get function will be executed. That defaultLoaction we refer as a read-only property.

If you want to set the of property from the outside we define setter (line 24).

--

--

Amila Devin

BSc (Hons) in Information Technology Specialising in Software Engineering undergraduate at SLIIT