Object basics and Object iteration.
for...in
loopif...in
statementIn 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.
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
).
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.
For these exercises, create:
And use the developer tools in chrome to run and monitor the script.
<html>
<head>
<title>JavaScript Test Site</title>
<script src="objects-09.js"></script>
</head>
<body>
<p>Nothing going on yet.</p>
</body>
</html>
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!
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"
}
*/
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"
}
*/
Use the files you created earlier:
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.
Use the files you created earlier:
Experiment with the following:
title
, and log the fields againSometimes, 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!");
}
Use the files you created earlier:
Experiment with the following:
=>
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
Using the files you created earlier:
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,
};
7
.delete
keyword, write the command to remove the artist key from the playList object.oldSchool
and a value of true
to the playList object.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]);
}