JavaScript object basics

JavaScript is an object oriented programming language. An object is a collection of properties and these properties can be either primitives or other objects, including functions. Unlike most other object oriented programming languages, which are based on classes and class instances, JavaScript is based on prototypal inheritance in which objects inherit from other objects. So, these objects make it much easier to manage in your programs.

Creating Objects in JavaScript

There are a number of ways you can create your own objects in JavaScript . An object can be created with figure brackets {…} with an optional list of properties. A property is a "key: value" pair, where key is a string (also called a "property name"), and value can be anything. example
var student = { ID:1001, name: "John", getName: function() { alert(; } }; student.getName();
Here you can see, student is an Object and ID and name are Object properties and getName() is the method in the Object.

Creating Object with "new" keyword

var student = new Object(); student.ID = 1002; = "Jack"; alert(;

Creating Object from Object Constructor

function student(id,name){ = id; = name; } student1 = new student(1001,'David'); alert(;

Method in JavaScript Object

Methods can define inside Javascript Objects . But before defining method, we need to add property in the function with same name as method.
function student(id,name){ = id; = name; this.getDetails = getDetails; function getDetails() { return "ID: " + + " , Name : " +; } } student1 = new student(1001,'David'); alert(student1.getDetails());

Object contain another Object

In JavaSript, an Object can contain any data, including other objects too.

var student = { name: "John", age: 14, classTeacher: { fName: "Jack", lName: "Danile" } }; alert(student.classTeacher.fName); alert(student['classTeacher']['fName']); alert(student.classTeacher['fName']); alert(student['classTeacher'].fName);