Basic Javascript - 1
Basic Javascript - 1
Basic Javascript - 1
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!"]
};
var myDog = {
};
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"
};
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 = {
};
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"
};
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!"]
};
// Setup
var myDog = {
"name": "Coder",
"legs": 4,
"tails": 1,
};
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 = {
"legs": 4,
"tails": 1,
};
"legs": 4,
"tails": 1,
"friends": ["everything!"],
"bark": "bow-wow"
};
delete ourDog.bark;
// Setup
var myDog = {
"legs": 4,
"tails": 1,
"bark": "woof"
};
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) {
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";
return result;
phoneticLookup("charlie");
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) {
checkObj("gift");
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 = [
"release_year": 1973,
"gold": true
];
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": {
},
"outside": {
"trunk": "jack"
};
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"
]
}
];