Object Basics in JavaScript

Danushka Malinga
3 min readMar 17, 2022

--

What you saw in the code above?

It is a JavaScript object literal. Yes the object thing you heard in programming. In this blog article we are going to look ,what is an object in JavaScript and how its behave in JavaScript environment.

Nearly everything in JavaScript is an object. There is a reason to it. Before understand it, lets start from scratch.

What is an object?

An object is a collection of related data and/or functionality. These usually consist of several variables and functions (which are called properties and methods when they are inside objects).

How to create an object?

The first step in object creation is, define and initializing a variable.

Now we have an object. But this is an empty object. So we cant do much things we the empty object. Lets create a meaningful object.

Ok now we got some data and functionality inside our object. These are we call as members. So object consist with multiple members. Each of every member has a key and a value. And key value pairs are separated with comma. When we look at the above code, we can see various types of values. We call above object as an object literal.

How to access object properties?

To access an object property, There are two ways. One is Dot Notation and other is Bracket Notation.

Dot Notation
Bracket Notation

Why we need ‘Factory Functions’ and ‘Constructor Functions’?

We learnt that by using object literal syntax we can create an object. But when the object consist with more than one method, the object starts its behavior. Then its not good to use an object literal to create an object. Therefore we use factory function and constructor function to create an object.

Factory Function

If function return an object we should call it as factory function.

Factory function

The above code shows the function called createBlog() and it returns an object.

Constructor Function

If function use this keyword and new keyword to call that function, We should call it as constructor function. But before we understand the constructor function lets understand what is this and new keywords for,

what is “this”?

The this keyword refers to the current object the code is being written inside

What is “new”?

New keyword in JavaScript is used to create an instance of an object that has a constructor function

Constructor function

we use CamalCase to name the constructor function name. In here we don't use explicit return statement because in underlying new keyword provides return statement.

Thank you.

--

--

No responses yet