Exercises: JavaScript Objects
Standard Exercises
0. What does the following code do? What do you think it prints out? Try it out and see.
var person = {
firstName: "John",
lastName: "Wordsworth"
};
console.log(person.firstName);
console.log(person["lastName"]);1. What does the following code do? What do you expect it to print out?
var contact = {};
contact["fullName"] = "John Wordsworth";
contact["mobile"] = "01234567890";
console.log(contact.fullName + " " + contact.mobile);2. You can access an object's properties using either a dot followed by the name of the property object.property or by using square brackets containing a string with the property name object["property"]. Like with an array, you can read or write to properties this way. Conver the following code to use the square brackets format for accessing object properties;
var tweet = {
username: "@JohnWordsworth",
message: "Hello Everyone!",
likes: 6
}
console.log( tweet.username ); // Should print "@JohnWordsworth"
console.log( tweet.message ); // Should print "Hello Everyone!"3. Similarly, convert the following code to use the dot format instead of square brackets.
var tweet = {
username: "@JohnWordsworth",
message: "Goodbye Everyone!",
likes: 0
}
console.log( tweet["username"] + " tweeted " + tweet["message"] );4. Create a variable called song as an object to represent a song in a music player. The song object should have the properties "title" and "artist". Use the following code to ensure you have created your object correctly;
// Define your song object here
console.log( song.title );
console.log( song.artist );5. Write the function printContactName(contact); that takes an object and prints out the 'name' property of that object if it is not null. Test your function with the following code;
var contact1 = {
name: "John Wordsworth",
address: "1 Infinite Loop"
};
var contact2 = {
address: "2 Infinite Loop",
};
printContactName(contact1); // Should print "John Wordsworth"
printContactName(contact2); // Should not print anything (as it has no name)Advanced Exercises
6. Now it's time to create an array containing objects. Create a variable called playlist which is an array containing 3 song objects. Each song object should have a 'title' and 'artist' property. Use 3 songs that you love!
// Declare variable 'playlist'
console.log(playlist.length); // Should print '3'
console.log(playlist[0].title); // Should print the title of your first song
console.log(playlist[2].artist); // Should print the title of your third song7. Use a for loop to print the title of every object in your playlist on a separate line.
8. Turn your previous answer into a function called printPlaylist(playlist); which will print the title of every song in a playlist.
console.log("Hello World");