Social Icons

Pages

Wednesday, November 30, 2016

Introduction to Objects I 11/33

Putting it all together
We've learned how to make objects in two different ways. Both are valid, and you can use which one you prefer.
Let's practice how to use both one more time.

Instructions
Use literal notation to finish the snoopyobject. Remember literal notation is the one where we fill in } with separate properties and values with colons. Each property is separated by a comma.
snoopy should have two properties, aspecies of "beagle" and age of 10.
Then make buddy, a 5 year-old golden retriever, using constructor notation. This notation involves using the key word new to create an empty object. Then we fill it in using dot notation.
// help us make snoopy using literal notation
// Remember snoopy is a "beagle" and is 10 years old.
var snoopy ={
    species:"beagle",
    age:10,
};

// help make buddy using constructor notation
// buddy is a "golden retriever" and is 5 years old
var buddy = new Object()
buddy.species="golden retriever";
buddy.age=5;


Introduction to Objects I 10/33

Another Way to Create
The method we've used to create objects usesobject literal notation—that is, creating a new object with { } and defining properties within the brackets.
Another way of creating objects without using the curly brackets { } is to use the keywordnew. This is known as creating an object using a constructor.
The new keyword creates an empty object when followed by Object(). The general syntax is:
var objectName = new Object();
We then have to fill this object with properties and labels. How do we do that? Check out the creation of the object bob to see what we do. We create the name property for the objectbob by using bob.name and assigning that to a value. Contrast this to how we define properties in lines 6-7 for the susan1 object.

Instructions
Inspect the susan1 object carefully and note the use of object literal notation.
Use constructor notation to create susan2, which should have the same properties and values as susan1.

// Our bob object again, but made using a constructor this time
var bob = new Object();
bob.name = "Bob Smith";
bob.age = 30;
// Here is susan1, in literal notation
var susan1 = {
  name: "Susan Jordan",
  age: 24
};
// Make a new susan2 object, using a constructor instead
var susan2 = new Object();
susan2.name = "Susan Jordan";
susan2.age = 24;

Introduction to Objects I 9/33

Accessing Properties, Part 2
In the last exercise, we accessed properties using what is known as dot notation. Good name, right? So to access a property, we useObjectName.PropertyName (e.g., bob.name)
In addition to dot notation, we can also access properties using bracket notation. In this case we use ObjectName["PropertyName"] to access the desired property. Note, we need " " around the property's name.
Take a look at our next example object calleddog. Notice on line 8 how we save the dog's species into a variable by accessing thespecies property of dog using bracket notation.

Instructions
Use bracket notation to save the dog's weightand age into variables as well.

// Take a look at our next example object, a dog
var dog = {
  species: "greyhound",
  weight: 60,
  age: 4
};

var species = dog["species"];
// fill in the code to save the weight and age using bracket notation
var weight =dog["weight"];
var age =dog["age"];

Introduction to Objects I 8/33

Accessing Properties
Now that we know how to make objects with properties, let's look at how we actually use them!
Notice our example objects bob and susan. In this case both bob and susan each have two properties, name and age.
After creating our objects we have added code to access these properties. Notice that we save bob's name, "Bob Smith", into the global variable name1. We do this in line 10.

Instructions
Finish the exercise by filling in the code inlines 13 and 14 to access the name and agefor susan and save those into the given global variables.

var bob = {
  name: "Bob Smith",
  age: 30
};
var susan = {
  name: "Susan Jordan",
  age: 25
};
// here we save Bob's information
var name1 = bob.name;
var age1 = bob.age;
// finish this code by saving Susan's information
var name2 =susan.name;
var age2 =susan.age;

Introduction to Objects I 7/33

Properties
Let's review what we previously covered. Each piece of information we include in an object is known as a property. Think of a property like a category label that belongs to some object. When creating an object, each property has a name, followed by : and then the value of that property. For example, if we want Bob's object to show he is 34, we'd type in age: 34.
age is the property, and 34 is the value of this property. When we have more than one property, they are separated by commas. The last property does not end with a comma.

Instructions
See the console for the object I have created about myself. Can you create an object calledme that describes your age and which country you live in?

var Spencer = {
  age: 22,
  country: "United States"
};
var me = {
  age: 18,
  country: "United States"
};

Introduction to Objects I 6/33

Intro
We have discussed four data types: numbers, strings, booleans and arrays.
In this lesson, we focus on a fifth data type:objects. This data type is a little bit more complex. Objects allow us to represent in code real world things and entities (such as a person or bank account). We do this by storing all relevant information in one place—an object.
How do we create an object? Like declaring a variable, or defining a function, we use var, followed by the name of the object and an equals sign. Each object then:
starts with {
has information inside
ends with };

Instructions
Create an object called bob that has no information inside the brackets.
var bob = Object();

Introduction to Objects I 5/33

I have to praise you like I should!
Congratulations for making it this far! We hope you're enjoying the courses and feel more comfortable programming in JavaScript.
We have a number of exciting things in store for you and can't wait to roll them out!

Instructions
If you're ready to start learning about objects, print in the console: "I'm ready for Objects!"

console.log("I'm ready for Objects!");

Introduction to Objects I 4/33

I have to celebrate you baby
This exercise has lots of movies and reviews to type in. You might wonder, "Is this teaching coding or typing?!"
But there's a reason why there are so many cases to deal with. We want to show that if we used if-else statements, it would be inefficient. What alternative to if / else can we use?

Instructions
Imagine you have a movie collection, and you want to write code that returns your review for each one. Here are the movies and your reviews:
  • "Toy Story 2" - "Great story. Mean prospector."
  • "Finding Nemo" - "Cool animation, and funny turtles."
  • "The Lion King" - "Great songs."
Write a function named getReview that takes in a movie name and returns its review based on the information above. If given a movie name not found just return "I don't know!". Use a structure learned in an earlier lesson (NOT if/else statements) to write this function.

var getReview = function (movie) {
switch(movie) {
    case "Toy Story 2":
    return "Great story. Mean prospector.";
    break;
        case "Finding Nemo":
        return  "Cool animation, and funny turtles."
        break;
        
        case "The Lion King":
        return  "Great songs."
        break;
        
        default:
        return "I don't know!"
        break;
}

};
getReview("The Lion King");


Introduction to Objects I 3/33

And the good!
We're going to play a game of FizzBuzz. The rules are simple. We want to count from 1 to 20. But if the number is divisible by 3, we're going to print "Fizz". And if the number is divisible by 5 we're going to print "Buzz".
What will we print if the number is divisible by 3 AND 5? That's right! "FizzBuzz"!
There are many ways to do this, but we'd like you to use a nested conditional in this exercise.

Instructions
  1. Print out the numbers from 1 - 20.
  2. The rules:
    • For numbers divisible by 3, print out "Fizz".
    • For numbers divisible by 5, print out "Buzz".
    • For numbers divisible by both 3 and 5, print out "FizzBuzz" in the console.
    • Otherwise, just print out the number.
?
Hint
  1. Use a for loop to iterate through the numbers 1 to 20.
  2. Use an if / else to check if the number is divisible by 3 or 5
  3. Log to the console either "Fizz","Buzz", or "FizzBuzz".
Here is how to use an if/else statement:
if(condition) {
    // Do one thing here
}
else {
    // Do another thing here
}

                                                      for(i=1;i<21;i++)
                                                       {
                                                          if(i%3==0&&i%5==0){console.log("FizzBuzz");}
                                                               else if (i%5==0){console.log("Buzz");}
                                                                   else if (i%3==0){console.log("Fizz");}
                                                                      else{console.log(i);}

                                                       };



Introduction to Objects I 2/33

Through the hard times...
We know two ways of storing data types. We can use variables or arrays. We use variables to store data (like strings or numbers) that we’d later want to access.
An array is exactly the same as a variable in that it stores data. The difference is that an array can store many more values while a variable can only store one.
To access arrays, we use bracket notation and remember that arrays use 0-based indexing (i.e., the first value in an array is at position 0).

Instructions
Look at the array multiplesOfEight, and find the one that doesn't fit.
Replace X in line 6 such that the variableanswer is assigned the Boolean value of true.
?
Hint
Array indexes start at 0. So the first element of an array has index 0.
For example, the first element ofmultiplesOfEight is 8, and its index is 0. The third element of multiplesOfEight is24, and its index is 2.
The operator !== means "does NOT equal". For example,
10 !== 5;
evaluates to true because 10 does not equal 5.


// Here is an array of multiples of 8. But is it correct?
var multiplesOfEight = [8,16,24,32,40,58];
var X= multiplesOfEight 

// Test to see if a number from the array is NOT a true
// multiple of eight. Real multiples will return false.
var answer = multiplesOfEight[X] % 8 !== 0;

Introduction to Objects I 1/33

We've come a long, long...
If yellow triangle warnings appear in the editor next to any code we provide in any exercise, it is fine to ignore them.
The very basic building block of JavaScript are primitive data types. We know of three primitives:
strings (e.g. "dogs go woof!")
numbers (e.g. 4, 10)
booleans (e.g. false, 5 > 4)
We learned about the use of comparators (eg.>, <=, !==, etc.). One really important thing to note is that any time comparisons are made, a Boolean value is returned.

Instructions
There is a long and ugly expression in the editor. Overall, it evaluates to a Boolean (i.e., either the entire statement is true, or it isfalse).
What does this expression in the editor evaluate to?
Declare a variable named answer. Assign to it the Boolean value that the expression evaluates to. Delete the default code in the editor and run your code.

var answer =(((3 * 90) === 270) || !(false && (!false)) || "bex".toUpperCase() === "BEX");













Tuesday, November 29, 2016

Building an Address Book 6/6!

var bob = {
firstName: "Bob",
lastName: "Jones",
phoneNumber: "(650) 777-7777",
email: "bob.jones@example.com"
};

var mary = {
firstName: "Mary",
lastName: "Johnson",
phoneNumber: "(650) 888-8888",
email: "mary.johnson@example.com"
};

function list() {
var contactsLength = contacts.length;
for (var i = 0; i < contactsLength; i++) {
printPerson(contacts[i]);
}
};

function search (lastName) {
var contactsLength = contacts.length;
for(var i=0; i<contactsLength; i++){
if(contacts[i].lastName === lastName){
printPerson(contacts[i]);
}
}
};

var add= function(firstName, lastName, phoneNumber, email){
contacts[contacts.length] = {
firstName: firstName,
lastName: lastName,
phoneNumber: phoneNumber,
email: email
}
};
add("ade", "omo", "(650) 888-888", "andela@gmail.com");

list("ade");

Building an Address Book 5/6!

Finding that Special Someone
Let's say we're looking for someone in our address book with a specific last name.
We can do this with a technique for searching arrays called "linear search". With it, we use a loop to check through all of the items in the array one-by-one until we see the item that we want.
We can apply linear search to print out all of the people that have a particular last name.


Instructions
We'll be creating a function that can search for people with a specific last name and print those people out with the printPersonfunction.
  1. Create a function called search that takes a parameter called lastName. Leave the listfunction alone.
  2. Like with the last exercise, define a variable and store the number of items in the array in it. (Since every function has its own context, or scope, you can call this variablecontactsLength, too, if you like!)
  3. Create a for loop that runs through all of the items in the array. For this step, the code for search is identical to that of list.
  4. The twist comes here: in the body of the loop, rather than printing out every single item in the array, add an if statement that checks to see if the lastName property of the object is equal to the lastName argument. Have the function run printPerson on the person if and only if the lastName property of the person matches the lastName argument.
  5. At the bottom of the file, call the searchfunction, passing in "Jones" as the last name to search for.c


var bob = {
    firstName: "Bob",
    lastName: "Jones",
    phoneNumber: "(650) 777-7777",
    email: "bob.jones@example.com"
};

var mary = {
    firstName: "Mary",
    lastName: "Johnson",
    phoneNumber: "(650) 888-8888",
    email: "mary.johnson@example.com"
};

var contacts = [bob, mary];

function printPerson(person) {
    console.log(person.firstName + " " + person.lastName);
}

function list() {
    var contactsLength = contacts.length;
    for (var i = 0; i < contactsLength; i++) {
        printPerson(contacts[i]);
    }
}

/*Create a search function
then call it passing "Jones"*/
function search(lastName) {
    for (var i = 0; i < contacts.length; i++) {
        if (contacts[i].lastName === lastName) {
            printPerson(contacts[i]);    
        }    
    }    
};
console.log(contacts.length);
search("Jones");