Object creation in JavaScript

The blog describes how to create objects in JavaScript. The JavaScript object is an entity  with state and behavior i.e. defines properties and methods. The objects in JavaScript can be created as given below

  • By using Literals and Properties
  • By creating an instance of an object
  • By creating an Object Constructor

JavaScript Object creation using Literals and Properties

An object can store the keyed collection of data. An object is created using Literals and properties . An object is surrounded with { } with the list of properties where a property is a key: value pair . A key is also called as property name.

Lets understand it with further examples

JavaScript supports creation of empty object as given below using literals and new Object ()

let student = new Object(); // "object constructor" syntax
let student = {};           // "object literal" syntax

Now lets consider another example where a student object is created and property name (key) and value is provided

let student = {     		// where student is an object
    studentId: 101			//where key "StudentId" store value as 101
    name: "Mohit Sharma",  	// where key "name" store value "Mohit Sharma"
    age: 30        			// where key "age" stores values as 30
	
	alert( student.studentId );     // returns 101
	alert( student.name ); 			// returns "Mohit Sharma"
	alert( student.age ); 			// returns 30
};

In the student object, we have define 3 properties

  1. studentId : where property name / key “StudentId” store value as 101
  2. name : where property name / key “name” store value “Mohit Sharma”
  3. age: where property name / key “age” stores values as 30

Remove Property from JavaScript Object

The created object properties can also be removed using the delete command

// Delete age property from the student object
delete student.age;

JavaScript Object creation through object instance

The object instance can be crated using the below given syntax

// new is used to create a new object
var objectname=new Object();  
<script>  
var student =new Object();  
student.studentId=101;  
student.name="Mohit Sharma";  
student.age= 30;  
document.write(student.studentId+" "+student.name+" "+student.age);  
</script>

JavaScript Object creation using constructor

The JavaScript objects can be created using the constructor as per the below given example.

<script>  
function student(studentId,name,age){  
this.studentId=studentId;  
this.name=name;  
this.age=age;  
}  
s=new student(101,"Mohit Sharma",30);  
  
document.write(s.studentId+" "+s.name+" "+s.age);  
</script>