Skip to content

Instantly share code, notes, and snippets.

@adilmezghouti
Last active August 29, 2015 13:59
Show Gist options
  • Save adilmezghouti/10690138 to your computer and use it in GitHub Desktop.
Save adilmezghouti/10690138 to your computer and use it in GitHub Desktop.
Javascript Beginner's series - Objects
var flight = {
airline: "Oceanic",
number: 815,
//you can have nested objects
departure: {
IATA: "SYD",
time: "2004-09-22 14:55",
city: "Sydney"
},
arrival: {
IATA: "LAX",
time: "2004-09-23 10:42",
city: "Los Angeles"
}
};
var name;
console.log("Here are the properties of my brand new object:");
for(name in flight){
console.log(name);
}
//------------------- How to retrieve object properties -----------------------------
console.log(flight.airline); //"Oceanic"
console.log(flight["airline"]); //"Oceanic"
console.log(flight.departure.IATA); //"SYD"
console.log(flight["departure"]["IATA"]); //"SYD"
//------------------- How to provide default values ---------------------------------
var status = flight.status || "unknown";
//------------------ How to guard against "undefined" throwing TypeError ------------
flight.equipment && flight.equipment.model
//----------------- How to update an object -----------------------------------------
flight.ariline = "Spirit Airlines";
console.log(flight.airline);
//if property does not exist, it will be added, this is called object augmentation
flight.equipment = {
model: 'Boeing 777'
};
flight.status = 'overdue';
console.log("Here is my updated flight: " + flight);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment