Understanding Objects in JavaScript

chessboard using javascript

Objects in JavaScript can be understood as a container. It has properties associated with it along with functions. Properties are the variables which can be used to save values and can be accessed using the dot(.) notation.


Let us see an example

var myLaptop = new Object();
myLaptop.make = "Apple";
myLaptop.model = "MacBook Pro";
myLaptop.year = 2013;

You can access the values the values by either using the dot notation or square brackets as shown below.

console.log(myLaptop.make); // outputs Apple
console.log(myLaptop.model); // outputs MacBook Pro
console.log(myLaptop.year); // outputs 2013;

console.log(myLaptop["make"]); // outputs Apple
console.log(myLaptop["model"]); // outputs MacBook Pro
console.log(myLaptop["year"]); // outputs 2013;

Please note that if an object’s property is a string with spaces in it or hyphen in its name or begins with a number, then it can only be accessed using the square brackets notation and not using the dot notation.

We can use for…in to iterate through all of the properties of the object using the bracket notation as shown in the example below.

var myObj={};

myObj.model="macbook pro";

var result="";

for(var i in myObj)
        result+=i+" > "+myObj[i]+"\n";

output will be

name > apple
model > macbook pro
year > 2013


Creating an Object

One of the ways to create an Object is to use a constructor function which will accept the values as parameters.

function createCar(name,model,year)

var myCar=new createCar("a","b", 100);


In JavaScript an object can be contained inside another object. We can modify the above code and pass an object with owner detail as the fourth argument.

function createCar(name,model,year,owner)

var owner={name:"John",city:"NYC"};
var myCar=new createCar("a","b", 100,owner);
console.log(myCar.owner.name);  // output will be John

NOTE: When you pass an object as an argument, don’t put it single or double quotes else it will be treated as a string.

Object.create method to create objects

Other than the method explained above regarding how to create objects, we can also use the create() method of Object to create another object.

The create() method accepts the prototype of the object for which we want to create our object.

/var Cars={

//Create a car object using the above defined object as a prototype.
var car1=Object.create(Cars);

var car2=Object.create(Cars);
car2.showType(); // output is SUV

Related Posts