3 weird ways to create javascript objects (Learn my tricks Now)

My connecting flight to Bangalore was delayed by 5  hours, and i was sitting in New Delhi airport, lazily watching the hustle and bustle of passengers.

Among my fellow passengers was one gentleman, who was sitting beside me. 

We were talking for the last 15 minutes. And he suddenly Asked, What Really Happened to Malaysian Airline flight MH370…

Let’s discover 3 ways to create object and find out what happened to MH370

1- Using the Object Literal Notation:-

To Create JavaScript Object with Object Literal Notation, you have to simply define the property and their values inside curly braces.

var flight = {
   name: 'MH370', 
   maker:'Boeing', 
   model:'777',
   crashDate: '8.March.2014',
   location: 'Indian Ocean',
   cause:'Pilot Suicide' };

// You can access the properties by dot notation or bracket notation 

console.log(flight.model);
console.log(flight['cause']);
// Expected output = '777'
// Expected output = 'Pilot Suicide'

//you can change or add new property by dot notation

flight.cause = 'unknown'; 
flight.pilotName = 'Zaharie Ahmad Shah'; 
console.log(flight.cause);
console.log(flight.pilotName);
//Expected output = 'unknown'
//Expected output = 'Zaharie Ahmad Shah'

2- Using the Object Constructor:-

To Create Javascript Object with a constructor function you need a ‘new’ keyword only.

var pilot = {
   name: 'Zaharie Ahmad Shah',
   age: 55,
};

var pilotWife = new Object(); 
   pilotWife.name = 'Faizah Shah';
   pilotWife.age = 45;
   console.log(pilotWife);

// Expected output = age: 45,
// Expected output = name: "Faizah Shah"  

3- Using the Object.create() :-

The only difference between constructor and Object.create is that it allows you to create an object with attributes. Let’s see below.

var pilot = {
   name: 'Zaharie Ahmad Shah',
   age: 55,
};

var pilotWife = Object.create(null); 
   pilotWife.name = 'Faizah Shah';
   pilotWife.age = 45;
   console.log(pilotWife);

// Expected output = age: 45,
// Expected output = name: "Faizah Shah"  

Learn more about object creation here: MDN

If you like this post and it was helpful, join me on Facebook

More Articles:-

The Ultimate guide to become a full stack web developer in 3 easy step

7 Amazing Array Methods to Boost your Javascript Skills Today

Tanisk Jha

Mission-Driven Self taught Software Developer with a passion for thoughtful UI Design, collaboration and writing.

Leave a Reply

Your email address will not be published. Required fields are marked *