Objects in JavaScripts

Everything except primitives is an object in JavaScript. An Object has properties and methods.

Creating objects

You can create objects in many ways in JavaScript as mentioned below.

  1. literal object
  2. using constructor e.g. new Object()
  3. using Object.create()

//creating objects using literals
let car1 ={
        make:"honda",
        price:20000,
        features:['abs','alarm']
    }

console.log(car1.make);
//output - honda

console.log("car 1 " + JSON.stringify(car1));
//output - car 1 {"make":"honda","price":20000,"features":["abs","alarm"]}

//create objects using new operator (constructor)
let car2 = new Object();
car2.make = "honda";
car2.price = 20000;
car2.features = ['abs','alarm'];

console.log("car 2 " + JSON.stringify(car2));
//output - car 2 {"make":"honda","price":20000,"features":["abs","alarm"]}

let car3 = new Array();
car3.push(car1);
car3.push(car2);
console.log("car 3 " + JSON.stringify(car3));
/*output - car 3 [{"make":"honda","price":20000,"features":["abs","alarm"]},
 {"make":"honda","price":20000,"features":["abs","alarm"]}]*/


/*similarly we can also create custom constructor and
then create an object using new operator */
let Car =  function(make,price,features){
    this.make=make;
    this.price = price;
    this.features = features;
}

let car4 = new Car("Honda", 20000, ['abs','alarm']);
console.log("car 4 " + JSON.stringify(car4));
//output - car 4 {"make":"Honda","price":20000,"features":["abs","alarm"]}

//create objects using Object.create(prototypeObject, propertiesObject) method
//Advantage of using this method is that we can specify if the property is writable
//and or enumerable
let propObject = {
    make:{value:"honda",writable:true,enumerable:true},
    price:{value:20000,writable:false,enumerable:true},
    features:{value:['abs','alarm'],writable:false,enumerable:true}
}
let car5 = Object.create(null,propObject);
console.log("car 5 " + JSON.stringify(car5));
//output - car 5 {"make":"Honda","price":20000,"features":["abs","alarm"]}

Access all properties and methods of the object

You can access all methods and properties of any object using below code.

//show all properties and methods

for (let key in car5){
    console.log (key, typeof car5[key],car5[key]);
}
// output 
/*
make string honda
price number 20000
features object [ 'abs', 'alarm' ]
*/

Youtube | Facebook | Twitter | Website Home | Online Grocery Shopping Brisbane