Classes and Objects in JavaScript

A class is a set or category of things having some property or attribute in common i.e., car is a class having similar properties such as color, engine, gear, model number etc.

The “class” construct allows us to define prototype-based classes.

Syntax for declaring a class:

Objects

Objects are the instance of classes i.e., Car is a class and Jaguar is an object of the Car class

Let’s consider a variable named person:

var person = “Sherlock Holms”;

Objects are also like variables but they can contain many values; like

this code assigns many values (Sherlock, Holms, male) to a variable named person:

var person = {name:”Sherlock”, title:”Holms”, gender:”male”};

The values are written as name:value pairs.

Object Definition

var person = {FirstName:”Sherlock”, lastName:”Holms”, age:50};

Spaces and line breaks are not important. An object definition can span multiple lines:

Object Properties

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

PropertyValue
firstNameJohn
lastNameDoe
age30

Accessing Object Properties

Object properties can be accessed in 2 ways:

  1. objectName.propertyName

or

2. objectName[“propertyName”]

Access Method 1

Output

Access Method 2