JS Objects

Objects

Objects are a data type that let us store a collection of properties and methods.

var objectName = { 
  propertyName: propertyValue,
  propertyName: propertyValue,
  ...
};
var aboutMe = {
  hometown: "Pasadena, CA",
  hair: "brown"
}; 
var lizzieTheCat = {
  age: 18,
  furColor: "grey",
  likes: ["catnip", "milk"],
  birthday: {"month": 7, "day": 17, year: 1994}
};

Objects Access

Access properties using "dot notation":

var aboutMe = {
  hometown: "Pasadena, CA",
  hair: "brown"
}; 

var myHometown = aboutMe.hometown;

Or using "bracket notation" (like arrays):

var myHair = aboutMe["hair"];

Non-existent properties will return undefined:

var myGender = aboutMe["gender"];

Changing Objects

Use dot or bracket notation with the assignment operator to change objects.

Change existing properties:

var aboutMe = {
  hometown: "Pasadena, CA",
  hair: "brown"
}; 
aboutMe.hair = "blue";

Or add new properties:

aboutMe.gender = "female";

You can also delete properties:

delete aboutMe.gender;

Arrays of Objects

Since arrays can hold any data type, they can also hold objects:

var myCats = [
  {name: "Lizzie", 
   age: 18},
  {name: "Daemon",
   age: 1}
];

for (var i = 0; i < myCats.length; i++) {
  var myCat = myCats[i];
  console.log(myCat.name + ' is ' + myCat.age + ' years old.');
}

Objects as Arguments

Just like other data types, objects can be passed into functions:

var lizzieTheCat = {
  age: 18,
  furColor: "grey",
  likes: ["catnip", "milk"],
  birthday: {"month": 7, "day": 17, year: 1994}
}

function describeCat(cat) {
  console.log("This cat is " + cat.age + " years old with " + cat.furColor + " fur.");
}

describeCat(lizzieTheCat);

Object methods

Object properties can also be functions. Object functions are called "methods".

var lizzieTheCat = {
  age: 18,
  furColor: 'grey',
  meow: function() {
    console.log('meowww');
  },
  eat: function(food) {
    console.log('Yum, I love ' + food);  
  },
  sleep: function(numMinutes) {
    for (var i = 0; i < numMinutes; i++) {
      console.log('z');
    }
  }
};

Call object methods using dot notation:

lizzieTheCat.meow();
lizzieTheCat.eat('brown mushy stuff');
lizzieTheCat.sleep(10);

Object pro tip

Object.keys() lists all the property names of an object in an array.

var lizzieTheCat = {
  age: 18,
  furColor: 'grey',
  meow: function() {
    console.log('meowww');
  },
  eat: function(food) {
    console.log('Yum, I love ' + food);  
  },
  sleep: function(numMinutes) {
    for (var i = 0; i < numMinutes; i++) {
      console.log('z');
    }
  }
};
Object.keys(lizzieTheCat); // ["age", "furColor", "meow", "eat", "sleep"]

Built-in Objects

JS provides several built-in objects:

  • Array
  • Array.isArray()
  • Number
  • Number()
    Number.parseInt()
    Number.parseFloat()
  • Date
  • Date.UTC()
    Date.now()
    Date.parse()
  • Math
    Sooooooooo many useful things!