Objectives

Object basics and Object iteration.

Object Basics

  • Compare and contrast objects and arrays, and explain good use cases for each one
  • Iterate over arrays and objects
  • Add and remove properties/elements from objects

Object Iteration

  • Understand how to iterate through an object using a for...in loop
  • Determine if a key exists in an object using an if...in statement

Object Basics I

Introduction

In JavaScript, along with primitives we have objects. Objects allow you to map keys to values. For example, the key 'name' could map to "Tim". Or the key 'isInstructor' could map to the boolean true. These are example of key value mappings. When you want to know the name property of the object, you look it up and get the value back, which is "Tim" in this case. Here is an example of declaring an object:

var firstObj = {
  firstName: "Tim",
  lastName: "Garcia",
  isInstructor: true
};

In this object, we have keys of "firstName", "lastName", and "isInstructor" and values of "Tim", "Garcia", and true respectively.

Notice the format of an object. It has a key, followed by a colon, followed by a value, then a comma. But the last key and value in the object omits the comma. Forgetting the comma is an error that you may run into from time to time. Try putting the following in your console. You should see an error, Uncaught SyntaxError: Unexpected identifier, because there is no comma after the firstName key and value:

var firstObj = {
  firstName: "Tim"
  lastName: "Garcia",
  isInstructor: true
};

After we have created an object, the first thing we may want to do with it is access the values using the object's keys.

Accessing Object Values

To access values in an object, we could use the dot notation:

firstObj.firstName;       // returns "Tim"
firstObj.lastName;        // returns "Garcia"
firstObj.isInstructor;    // returns true
firstObj.keyDoesntExist;  // returns undefined

Or we could use the bracket notation:

firstObj["firstName"];       // returns "Tim"
firstObj["lastName"];        // returns "Garcia"
firstObj["isInstructor"];    // returns true
firstObj["keyDoesntExist"];  // returns undefined

We will learn the difference between these two later on.

Objects are one of the built-in types in JavaScript and consist of unordered key-value pairs. Let's look at another object:

var tim = {
  name: "Tim",
  catOwner: true,
  boatOwner: true
};

In the object above we have a set of keys (name, catOwner, boatOwner) and values ("Tim", true and true).

Bracket Notation vs Dot Notation

If we want to access values in the object we can do it two different ways: either using brackets ([]) or dot notation. Let's take a look at both.

var obj = {
  firstName: "Elie",
  lastName: "Schoppik",
  favoriteColor: "purple",
  job: "instructor",
  isDeveloper: true
};

obj.firstName; // Elie
obj["lastName"]; // Schoppik
obj[favoriteColor]; // This gives us an error, because there is no variable called favoriteColor!

So which one should we use? Well, best practice is to use the dot notation if you can use it. But there are cases in which you'll need to use bracket notation. Let's take a look at this example:

var obj = {};
var person = "Tom";

obj[person] = "This is a person";
obj[1+1+1] = "Three";

obj;


/*
obj now should look like this: 
{
    Tom: "This is a person",
    3: "Three"
}
*/

obj.3;// Syntax Error! Can't use the dot notation with a number
obj[3]; // "Three" - we NEED to use the bracket notation
obj[person]; // "This is a person" it works because the var person has the name Tom contained in it.
obj["Tom"]; // "This is a person"
obj.person; // undefined this is because the key is not person it is Tom.

In short, use the bracket notation when you need to evaluate some expression or pass in a variable to get the name of the key, but when you know the name of the key and it is not a variable or expression, always use the dot notation.

Exercises

For these exercises, create:

  • objects-09.html
  • objects-09.js

And use the developer tools in chrome to run and monitor the script.

objects-09.html

<html> 
  <head>
    <title>JavaScript Test Site</title>
    <script src="objects-09.js"></script>
  </head>
  <body>
    <p>Nothing going on yet.</p>
  </body>
</html>

Exercise 1

  • Create a goMark object that has 'url', 'description', and 'rating' as keys. Initialise the object with some values and log to the console.

Object Basics II

Keys Are Always Strings in JavaScript

It is important to note that the type of a key in JavaScript is always a string. Let's say we create the following object of some employee id to the employee name:

var idToName = {
    754: "Tim",
    843: "Matt",
    921: "Janey",
    192: "Elie"
};

Now we want to access the key 754 to get the value "Tim". We cannot use the dot notation for this:

idToName.754;  // causes an error

Instead we need to use the bracket notation. And the value inside the bracket notation is a string:

idToName["754"];  // returns "Tim"

So even though we did not quote the key name when we created the idToName object, JavaScript automatically converts the number into a string. Every key in a JavaScript object is a string!

Adding to objects

To add properties or functions (which are sometimes called methods) to our objects, we can use the . or [] operator (as before, the dot notation is preferred, but not always possible).

var obj = {
  name: "Jon Snow",
  watchMember: true,
};

obj.gameOfThrones = "awesome";
obj;

/*
{
    name: "Jon Snow",
    watchMember: true,
    gameOfThrones: "awesome"
}
*/

Removing from objects

We can remove a key from an object by using the delete keywork. Here's an example:

var obj = {
  name: "Elie",
  job: "Instructor"
};

delete obj.job; // returns true

obj;

/*
{
    name: "Elie"
}
*/

Exercises

Use the files you created earlier:

  • objects-09.html
  • objects-09.js

Exercises 3: Dot and Bracket notation.

  • Access each value from your goMark object using both dot notation and brakcet notation.
  • Add a key for 'category' to your object. Remove the key and value for 'rating'.

Object Iteration I

Looping over objects

One of the most important ideas in programming is the idea of iteration, or looping. Let's say we want to print out all of the values in an object. One way we can do this is by printing the values individually, one per line.

var obj = {
  firstName: "Elie",
  lastName: "Schoppik",
  favoriteColor: "purple",
  job: "instructor",
  isDeveloper: true
};

console.log(obj.firstName);
console.log(obj.lastName);
console.log(obj.favoriteColor);
console.log(obj.job);
console.log(obj.developer);

Although this will work, there are cases where we don't know the keys that an object has. In that case, looping is a much better idea. Let's take a look at how we would loop over the keys in an object.

To iterate over objects, we use a for in loop.

var instructor = {
  name: "Matt",
  mathWizard: true,
  dogOwner: true
};

for (var singleKey in instructor) {
  console.log(instructor[singleKey]);
}

// the loop will log:
// "Matt"
// true
// true

In the code example, singleKey is a variable that will be assigned to each key in the instructor object. To access the key's value, we must use the bracket notation.

Exercises

Use the files you created earlier:

  • objects-09.html
  • objects-09.js

Exercise 3

Experiment with the following:

  • Log the GoMark objects fields using object iteration
  • after you have logged the fields, dynamically add a new field title, and log the fields again
  • after you have logged the field the second time, delete a field and log them again.

Object Iteration II

if...in: Determining If a Key Exists in an Object

Sometimes, we just want to check and see if a certain key exists in an object. To do that we use a if...in statement. Here is an example

var obj = {
    favoriteNumber: 33,
    favoriteColor: 'blue'
}

if ("favoriteNumber" in obj){
    console.log("The favoriteNumber key exists!");
}

// "The favoriteNumber key exists!"

if ("nothing" in obj){
    console.log("The nothing key exists!");
}

Exercises

Use the files you created earlier:

  • objects-09.html
  • objects-09.js

Exercise 4

Experiment with the following:

  • Given the following object below, write code to print the value then the key to the console separated by =>
const goMark = {
  url: "http://www.wit.ie",
  description: "third level educational institution",
  rating: 3,
};
// Output should be:
// http://www.wit.ie => url
// third level educational institution => description
// 3 => rating
  • Add a key of your name and a value for your the year you started in W.I.T.
  • Write an if statement that console.logs your name and the year you started in W.I.T to the console if the key of your name is contained in the object.

Exercises

Using the files you created earlier:

  • objects-09.html
  • objects-09.js

Exercise 5:

Experiment with the following:

For each of the exercises below, assume you are starting with the following playList object

const playList = {
  id: "01",
  title: "Beethoven Sonatas",
  artist: "Beethoven",
  songs: ["Piano Sonata No. 3", 
          "Piano Sonata No. 7", 
          "Piano Sonata No. 10"],
  rating: 4,
};
  1. Write the command to add the song "Paino Sonata 13" to the end of the songs array.
  2. Change the rating to the value of 7.
  3. Using the delete keyword, write the command to remove the artist key from the playList object.
  4. Write the command to add a new key called oldSchool and a value of true to the playList object.
  5. Using a loop, iterate through the songs array and console.log all of the songs.
  6. Using a loop, console.log all of the keys in the playList object.
  7. Using a loop, console.log all of the values in the playList object.

JS Objects Exercise Solutions

var programming = {
    languages: ["JavaScript", "Python", "Ruby"],
    isChallenging: true,
    isRewarding: true,
    difficulty: 8,
    jokes: "http://stackoverflow.com/questions/234075/what-is-your-best-programmer-joke"
}

// 1

programming.languages.push("Go");

// 2

programming.difficulty = 7;

// 3

delete programming.jokes;

// 4

programming.isFun = true;

// 5

for (var i = 0; i < programming.languages.length; i++) {
    console.log(programming.languages[i]);
}

// 6

for (var key in programming){
    console.log(key);
}

// 7

for (var key in programming){
    console.log(programming[key]);
}