Basic Javascript - 1

Download as pdf or txt
Download as pdf or txt
You are on page 1of 16

1.

Build JavaScript Objects


You may have heard the term object before.
Objects are similar to arrays, except that instead of using indexes to access and modify
their data, you access the data in objects through what are called properties.
Here's a sample object:
var cat = {
"name": "Whiskers",
"legs": 4,
"tails": 1,
"enemies": ["Water", "Dogs"]
};
Objects are useful for storing data in a structured way, and can represent real world
objects, like a cat.

Instructions
Make an object that represents a dog called myDog which contains the properties "name"
(a string), "legs", "tails" and"friends".
You can set these object properties to whatever values you want, as long "name" is a
string, "legs" and "tails" are numbers, and"friends" is an array.
// Example

var ourDog = {

"name": "Camper",

"legs": 4,

"tails": 1,

"friends": ["everything!"]

};

// Only change code below this line.

var myDog = {

};

2. Accessing Objects Properties with the Dot Operator

There are two ways to access the properties of an object: the dot operator (.) and bracket
notation ([]), similar to an array.
The dot operator is what you use when you know the name of the property you're trying to
access ahead of time.
Here is a sample of using the dot operator (.) to read an object property:
var myObj = {
prop1: "val1",
prop2: "val2"
};
var prop1val = myObj.prop1; // val1
var prop2val = myObj.prop2; // val2
Instructions
Read in the property values of testObj using dot notation. Set the variable hatValue equal to
the object property hat and set the variable shirtValue equal to the object property shirt.
// Setup

var testObj = {

"hat": "ballcap",

"shirt": "jersey",

"shoes": "cleats"

};

// Only change code below this line

var hatValue = testObj; // Change this line

var shirtValue = testObj; // Change this line

3. Accessing Objects Properties with Bracket Notation

The second way to access the properties of an object is bracket notation ([]). If the property of
the object you are trying to access has a space in it, you will need to use bracket notation.
Here is a sample of using bracket notation to read an object property:
var myObj = {
"Space Name": "Kirk",
"More Space": "Spock"
};
myObj["Space Name"]; // Kirk
myObj['More Space']; // Spock
Note that property names with spaces in them must be in quotes (single or double).
Instructions
Read the values of the properties "an entree" and "the drink" of testObj using bracket
notation and assign them to entreeValueand drinkValue respectively.
// Setup

var testObj = {

"an entree": "hamburger",

"my side": "veggies",

"the drink": "water"

};

// Only change code below this line

var entreeValue = testObj; // Change this line

var drinkValue = testObj; // Change this line

4. Accessing Objects Properties with Variables

Another use of bracket notation on objects is to use a variable to access a property. This can
be very useful for iterating through lists of the object properties or for doing the lookup.
Here is an example of using a variable to access a property:
var someProp = "propName";
var myObj = {
propName: "Some Value"
}
myObj[someProp]; // "Some Value"
Here is one more:
var myDog = "Hunter";
var dogs = {
Fido: "Mutt",
Hunter: "Doberman",
Snoopie: "Beagle"
}
var breed = dogs[myDog];
console.log(breed);// "Doberman"
Note that we do not use quotes around the variable name when using it to access the
property because we are using the value of the variable, not the name
Instructions
Use the playerNumber variable to lookup player 16 in testObj using bracket notation.
// Setup

var testObj = {

12: "Namath",

16: "Montana",

19: "Unitas"

};

// Only change code below this line;

var playerNumber; // Change this Line

var player = testObj; // Change this Line

5. Updating Object Properties

After you've created a JavaScript object, you can update its properties at any time just like you
would update any other variable. You can use either dot or bracket notation to update.
For example, let's look at ourDog:
var ourDog = {
"name": "Camper",
"legs": 4,
"tails": 1,
"friends": ["everything!"]
};
Since he's a particularly happy dog, let's change his name to "Happy Camper". Here's how we
update his object's name property:
ourDog.name = "Happy Camper"; or
ourDog["name"] = "Happy Camper";
Now when we evaluate ourDog.name, instead of getting "Camper", we'll get his new name,
"Happy Camper".
Instructions
Update the myDog object's name property. Let's change her name from "Coder" to "Happy
Coder". You can use either dot or bracket notation.
// Example

var ourDog = {

"name": "Camper",

"legs": 4,

"tails": 1,

"friends": ["everything!"]

};

ourDog.name = "Happy Camper";

// Setup

var myDog = {

"name": "Coder",

"legs": 4,

"tails": 1,

"friends": ["CodeQuotient Campers"]

};

// Only change code below this line.

6. Add New Properties to a JavaScript Object


You can add new properties to existing JavaScript objects the same way you would modify
them.
Here's how we would add a "bark" property to ourDog:
ourDog.bark = "bow-wow";
or
ourDog["bark"] = "bow-wow";
Now when we evaluate ourDog.bark, we'll get his bark, "bow-wow".

Instructions
Add a "bark" property to myDog and set it to a dog sound, such as "woof". You may use
either dot or bracket notation.
// Example

var ourDog = {

"name": "Camper",

"legs": 4,

"tails": 1,

"friends": ["everything!"]

};

ourDog.bark = "bow-wow";

// Setup

var myDog = {

"name": "Happy Coder",

"legs": 4,

"tails": 1,

"friends": ["CodeQuotient Campers"]

};

// Only change code below this line.

7. Delete Properties from a JavaScript Object

We can also delete properties from objects like this:


delete ourDog.bark;
Instructions
Delete the "tails" property from myDog. You may use either dot or bracket notation.
var ourDog = {
"name": "Camper",

"legs": 4,

"tails": 1,

"friends": ["everything!"],

"bark": "bow-wow"

};

delete ourDog.bark;

// Setup

var myDog = {

"name": "Happy Coder",

"legs": 4,

"tails": 1,

"friends": ["CodeQuotient Campers"],

"bark": "woof"

};

// Only change code below this line.

8. Using Objects for Lookups

Objects can be thought of as a key/value storage, like a dictionary. If you have tabular data, you
can use an object to "lookup" values rather than a switch statement or an if/else chain. This is
most useful when you know that your input data is limited to a certain range.
Here is an example of a simple reverse alphabet lookup:
var alpha = {
1:"Z",
2:"Y",
3:"X",
4:"W",
...
24:"C",
25:"B",
26:"A"
};
alpha[2]; // "Y"
alpha[24]; // "C"

var value = 2;
alpha[value]; // "Y"

Instructions
Convert the switch statement into a lookup table called lookup. Use it to lookup val and assign
the associated string to the resultvariable.
// Setup

function phoneticLookup(val) {

var result = "";

// Only change code below this line

switch(val) {

case "alpha":

result = "Adams";

break;

case "bravo":

result = "Boston";

break;

case "charlie":

result = "Chicago";

break;

case "delta":

result = "Denver";
break;

case "echo":

result = "Easy";

break;

case "foxtrot":

result = "Frank";

// Only change code above this line

return result;

// Change this value to test

phoneticLookup("charlie");

9. Testing Objects for Properties

Sometimes it is useful to check if the property of a given object exists or not. We can use the
.hasOwnProperty(propname) method of objects to determine if that object has the given
property name. .hasOwnProperty() returns true or false if the property is found or not.
Example
var myObj = {
top: "hat",
bottom: "pants"
};
myObj.hasOwnProperty("top"); // true
myObj.hasOwnProperty("middle"); // false
Instructions
Modify the function checkObj to test myObj for checkProp. If the property is found, return
that property's value. If not, return "Not Found".
// Setup

var myObj = {

gift: "pony",
pet: "kitten",

bed: "sleigh"

};

function checkObj(checkProp) {

// Your Code Here

return "Change Me!";

// Test your code by modifying these values

checkObj("gift");

10. Manipulating Complex Objects

Sometimes you may want to store data in a flexible Data Structure. A JavaScript object is one
way to handle flexible data. They allow for arbitrary combinations of strings, numbers,
booleans, arrays, functions, and objects.
Here's an example of a complex data structure:
var ourMusic = [
{
"artist": "Daft Punk",
"title": "Homework",
"release_year": 1997,
"formats": [
"CD",
"Cassette",
"LP" ],
"gold": true
}
];
This is an array which contains one object inside. The object has various pieces of metadata about
an album. It also has a nested"formats" array. If you want to add more album records, you can do
this by adding records to the top level array.
Objects hold data in a property, which has a key-value format. In the example above, "artist":
"Daft Punk" is a property that has a key of "artist" and a value of "Daft Punk".
JavaScript Object Notation or JSON is a related data interchange format used to store data.
{
"artist": "Daft Punk",
"title": "Homework",
"release_year": 1997,
"formats": [
"CD",
"Cassette",
"LP"
],
"gold": true
}
Note
You will need to place a comma in between every object in the array, unless it is the last object in
the array.
Instructions
Add a new album to the myMusic array. Add artist and title strings, release_year number, and a
formats array of strings.
var myMusic = [

"artist": "Billy Joel",

"title": "Piano Man",

"release_year": 1973,

"formats": [ "CS", "8T", "LP" ],

"gold": true

// Add record here

];

11. Accessing Nested Objects

The sub-properties of objects can be accessed by chaining together the dot or bracket
notation.
Here is a nested object:
var ourStorage = {
"desk": {
"drawer": "stapler"
},
"cabinet": {
"top drawer": {
"folder1": "a file",
"folder2": "secrets"
},
"bottom drawer": "soda"
}
}
ourStorage.cabinet["top drawer"].folder2; // "secrets"
ourStorage.desk.drawer; // "stapler"
Instructions
Access the myStorage object and assign the contents of the glove box property to the
gloveBoxContents variable. Use bracket notation for properties with a space in their name.
// Setup

var myStorage = {

"car": {

"inside": {

"glove box": "maps",

"passenger seat": "crumbs"

},

"outside": {

"trunk": "jack"

};

// Only change code below this line

var gloveBoxContents = ""; // Change this line


12. Accessing Nested Arrays

As we have seen in earlier examples, objects can contain both nested objects and nested
arrays. Similar to accessing nested objects, Array bracket notation can be chained to access
nested arrays.
Here is an example of how to access a nested array:
var ourPets = [
{
animalType: "cat",
names: [
"Meowzer",
"Fluffy",
"Kit-Cat"
]
},
{
animalType: "dog",
names: [
"Spot",
"Bowser",
"Frankie"
]
}
];
ourPets[0].names[1]; // "Fluffy"
ourPets[1].names[0]; // "Spot"
Instructions
Retrieve the second tree from the variable myPlants using object dot and array bracket
notation. // Setup
var myPlants = [
{
type: "flowers",
list: [
"rose",
"tulip",
"dandelion"
]
},
{
type: "trees",
list: [
"fir",
"pine",
"birch"
]
}
];

// Only change code below this line


var secondTree = ""; // Change this line

13. Record Collection


You are given a JSON object representing a part of your musical album collection. Each
album has several properties and a unique id number as its key. Not all albums have
complete information.
Write a function which takes an album's id (like 2548), a property prop (like "artist" or
"tracks"), and a value (like "Addicted to Love") to modify the data in this collection.
If prop isn't "tracks" and value isn't blank, update or set the value for that record album's
property.
Your function must always return the entire collection object.
There are several rules for handling incomplete data:
If prop is "tracks" but the album doesn't` have a "tracks" property, create an empty array
before adding the new value to the album's corresponding property.
If prop is "tracks" and value isn't blank, push the value onto the end of the album's existing
tracks array.
If value is blank, delete that property from the album.
// Setup
var collection = {
"2548": {
"album": "Slippery When Wet",
"artist": "Bon Jovi",
"tracks": [
"Let It Rock",
"You Give Love a Bad Name"
]
},
"2468": {
"album": "1999",
"artist": "Prince",
"tracks": [
"1999",
"Little Red Corvette"
]
},
"1245": {
"artist": "Robert Palmer",
"tracks": [ ]
},
"5439": {
"album": "ABBA Gold"
}
};
// Keep a copy of the collection for tests
var collectionCopy = JSON.parse(JSON.stringify(collection));

// Only change code below this line


function updateRecords(id, prop, value) {
return collection;
}
// Alter values below to test your code
updateRecords(5439, "artist", "ABBA");

You might also like