objects

In this module we'll talk about objects.

File Location

Make sure you're in the right spot:

            └── 3-JavaScript-Basics
                09-objects.js

Description

This is a cool time in your career because here is where you start to learn about the world of Objects and Object Oriented Programming. Most people really like it.

Objects are a data type that let us store a collection of properties and methods. Let's make some.

Object Literals

Here is the syntax for an object literal:

//1                //2
var bobAlcorn = {
    //3                    //4
    name             : "Bob Alcorn",
    age              : 59,
    vocation        : "Chief Operating Officer",
    isRetired        : false
};

Discuss

Key points about the code above: 1. It's created using the var keyword, like a variable 2. It gets wrapped in curly braces: { }. 3. name, age, vocation, and isRetired are properties of the object. 4. Each of the properties has a value following the colon.

Dot Notations

In coding the dot . is an operator, like a plus symbol. It gives you access inside the object. When we use the object's name, then the ., we can see inside at the properties and access their values. Check it out:

console.log(bobAlcorn); //1
console.log(bobAlcorn.name); //2
console.log(bobAlcorn.age); //3
  1. Prints the whole object

  2. Prints the object, then the value for the name property.

  3. Prints the age property of the particular object.

Undefined

It's good to know about undefined. When we try to access a property that doesn't exist, we get undefined:

console.log(bobAlcorn.middleName); //undefined bc this property does not exist

Practice and Understanding

  1. Get a feel for it and go ahead and console.log(bobAlcorn);, the object's full name.

  2. Also, try console.log(bobAlcorn.age);.

  3. Then, create another object literal called player.

  4. Add properties called username, power, and toughness.

  5. Add values for each one of those properties.

  6. Print out the value of the player's username.

More Practice

Try to make a few more objects with properties. Get the syntax down and have fun. Try to have a few of these ready for the first day. Here are a few more ideas:

  • Make a friend object with at least four properties.

  • Make another object called movie with 3 properties

  • Make an object about anything you want (recipe, car, sports team).

Last updated