JavaScript Lesson 33: Creating an Object Using Literal Notation

Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedInEmail this to someone

<Previous Lesson> [Table of Contents] <Next Lesson>


An object is something that has properties and methods. For example, a car has properties like color, model, and methods such as start, accelerate and stop.

An object in JavaScript also has properties and methods. A JavaScript object actually comprises variables and functions. A variable inside an object is called a property and a function inside an object is called a method.

Creating an Object

There are two ways to create a JavaScript object, namely using literal notation and using object constructor notation

1. Using Literal Notation

The syntax to create an object is

var objectName={

MyMethod: MyFunction(){ }


Example 1.1

<!DOCTYPE html>

<p>The Phone Object.</p>

<h3>Model:<b id="model"></b></h3>
<h3> Brand:<b id="brand"></b></h3>
<h3>Price:<b id="price"></b></h3>

var phone= {model:"Note8", brand:"Samsung", color:"white",price:"$2000"};
document.getElementById("model").innerHTML = phone.model;
document.getElementById("brand").innerHTML = phone.brand;
document.getElementById("price").innerHTML = phone.price;


The output

The Phone Object.





The following example comprises a function:

Example 1.2

var student={
bmi: function(){
var x=this.weight/Math.pow(this.height,2);
var y=x.toFixed(2);
return y;

var student_Name=document.getElementById('studentname');;
var student_bmi=document.getElementById('bmi_index');

The object is student that comprise properties name, height, and weight. Its method is bmi that calculates the bmi index of a particular student. Notice that each property comprises name:value pairs and must be separated by a comma.


The output

Student Name:


<Previous Lesson> [Table of Contents] <Next Lesson>


Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedInEmail this to someone