Introduction to Objects in JavaScript

JavaScript is an Object Oriented Programming (OOP) language. A programming language can be called object-oriented if it provides four basic capabilities to developers −

  • Encapsulation − the capability to store related information, whether data or methods, together in an object.
  • Aggregation − the capability to store one object inside another object.
  • Inheritance − the capability of a class to rely upon another class (or number of classes) for some of its properties and methods.
  • Polymorphism − the capability to write one function or method that works in a variety of different ways.

Objects are composed of attributes. If an attribute contains a function, it is considered to be a method of the object, otherwise the attribute is considered a property. Loosely speaking, objects in JavaScript may be defined as an un-ordered collection of related data, of primitive or reference types, in the form of “key:value” pairs. These keys can be variables or functions and are called properties and methods, respectively, in the context of an object.

In JavaScript, almost “everything” is an object.

  • Booleans can be objects (if defined with the new keyword)
  • Numbers can be objects (if defined with the new keyword)
  • Strings can be objects (if defined with the new keyword)
  • Dates are always objects
  • Maths are always objects
  • Regular expressions are always objects
  • Arrays are always objects
  • Functions are always objects
Creating a JavaScript Object –

With JavaScript, you can define and create your own objects. There are different ways to create new objects:

  • Define and create a single object, using an object literal.
  • Define and create a single object, with the keyword new.
  • Define an object constructor, and then create objects of the constructed type.
Using an Object Literal –

This is the easiest way to create a JavaScript Object. Using an object literal, you both define and create an object in one statement. An object literal is a list of name:value pairs (like age:50) inside curly braces {}.

Program Example –

Using the JavaScript Keyword new –

The following example also creates a new JavaScript object with four properties:

Using the object constructor function –

Using the object constructor function you can create a template and then create multiple objects using that constructor function. Check the example below –

Object Properties –

The name:values pairs in JavaScript objects are called properties:

PropertyProperty Value
Accessing Object Properties –

You can access object properties in two ways:

Object Methods –

Objects can also have methods. Methods are actions that can be performed on objects.

PropertyProperty Value
fullNamefunction() {return this.firstName + ” ” + this.lastName;}
Accessing Object Methods –

You access an object method with the following syntax:


Leave a Reply

Your email address will not be published. Required fields are marked *