JavaScript Tutorial JavaScript Examples CSS Tutorial HTML Tutorial About Us

Lesson 33: Creating Object Part 1

33.1 Introduction

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.

33.2 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 33.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 33.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 Next Lesson ❯

Copyright©2008 Dr.Liew Voon Kiong. All rights reserved |Contact|Privacy Policy