Thursday, June 20, 2013

Python : Exam Statistics


grades = [100, 100, 90, 40, 80, 100, 85, 70, 90, 65, 90, 85, 50.5]

def print_grades(grades):
    for grade in grades:
        print grade

def grades_sum(grades):
    total = 0
    for grade in grades:
        total += grade
    return total
   
def grades_average(grades):
    sum_of_grades = grades_sum(grades)
    average = sum_of_grades / len(grades)
    return average
   

def grades_variance(grades, average):
    variance = 0
    for i in grades:
        variance += (average - i) ** 2
    return variance / len(grades)

def grades_std_deviation(variance):
    std_dev = variance ** 0.5
    return std_dev
   
print print_grades(grades)
print grades_sum(grades)
print grades_average(grades)
print grades_variance(grades,grades_average(grades))
print grades_std_deviation(grades_variance(grades, grades_average(grades)))

Friday, June 14, 2013

Python : Battleship


import random

board = []
for x in range(5):
    board.append(["O"] * 5)
def print_board(board):
    for row in board:
        print " ".join(row)
print "Let's play Battleship!"
print_board(board)
def random_row(board):
    return random.randint(0, len(board) - 1)
def random_col(board):
    return random.randint(0, len(board[0]) - 1)
ship_row = random_row(board)
ship_col = random_col(board)
print ship_row
print ship_col
# Everything from here on should go in your for loop!
# Be sure to indent four spaces!
for turn in range(4):
    guess_row = input("Guess Row:")
    guess_col = input("Guess Col:")
    if guess_row == ship_row and guess_col == ship_col:
        print "Congratulations! You sunk my battleship!"
        break
    else:
        if turn > 3:
            print "Game Over"
        else:

            if (guess_row < 0 or guess_row > 4) or (guess_col < 0 or guess_col > 4):
                print "Oops, that's not even in the ocean."
            elif(board[guess_row][guess_col] == "X"):
                print "You guessed that one already."
            else:
                print "You missed my battleship!"
                board[guess_row][guess_col] = "X"
    print "You have", (3-turn), "turns remain."
    #    print_board(board)

Saturday, June 8, 2013

Python : Student Becomes Teacher




lloyd = {
    "name": "Lloyd",
    "homework": [90.0, 97.0, 75.0, 92.0],
    "quizzes": [88.0, 40.0, 94.0],
    "tests": [75.0, 90.0]
}
alice = {
    "name": "Alice",
    "homework": [100.0, 92.0, 98.0, 100.0],
    "quizzes": [82.0, 83.0, 91.0],
    "tests": [89.0, 97.0]
}
tyler = {
    "name": "Tyler",
    "homework": [0.0, 87.0, 75.0, 22.0],
    "quizzes": [0.0, 75.0, 78.0],
    "tests": [100.0, 100.0]
}

# Add your function below!
def average(x):
    return sum(x) / len(x)

* * *

def get_average(student):
    return average(student["homework"]) * 0.1 + average(student["quizzes"]) * 0.3 + average(student["tests"]) * 0.6

def get_letter_grade(score):
    if score >= 90:
        return "A"
    elif score  >= 80:
        return "B"
    elif score >= 70:
        return "C"
    elif score >= 60:
        return "D"
    else:
        return "F"

print get_letter_grade(get_average(lloyd))

def get_class_average(students):
    student_averages = []
    for i in students:
        student_averages.append(get_average(i))
    return average(student_averages)

students = [lloyd, alice, tyler]

print get_class_average(students)

Thursday, June 6, 2013

Python : Taking a Vacation



def hotel_cost(nights):
    return nights * 140

def plane_ride_cost(city):
    if city == "Charlotte":
        return 183
    elif city == "Tampa":
        return 220
    elif city == "Pittsburgh":
        return 222
    elif city == "Los Angeles":
        return 475

def rental_car_cost(days):
    per_day = days * 40
    if days >= 7:
        return per_day - 50
    elif days >= 3:
        return per_day - 20
    else:
        return per_day

def trip_cost(city, days, spending_money):
    return rental_car_cost(days) + hotel_cost(days) + plane_ride_cost(city) + spending_money
 
print trip_cost("Los Angeles", 5, 600)

# return trip

def hotel_cost(nights):
    return nights * 140

bill = hotel_cost(5)

def add_monthly_interest(balance):
    return balance * (1 + (0.15 / 12))

def make_payment(payment, balance):
    new_balance = add_monthly_interest(balance - payment)

    return "You still owe: " + str(new_balance)
 
hotel_cost(5)  
print make_payment(100, hotel_cost(5) )

Wednesday, June 5, 2013

PEP 20


    Beautiful is better than ugly.
    Explicit is better than implicit.
    Simple is better than complex.
    Complex is better than complicated.
    Flat is better than nested.
    Sparse is better than dense.
    Readability counts.
    Special cases aren't special enough to break the rules.
    Although practicality beats purity.
    Errors should never pass silently.
    Unless explicitly silenced.
    In the face of ambiguity, refuse the temptation to guess.
    There should be one-- and preferably only one --obvious way to do it.
    Although that way may not be obvious at first unless you're Dutch.
    Now is better than never.
    Although never is often better than *right* now.
    If the implementation is hard to explain, it's a bad idea.
    If the implementation is easy to explain, it may be a good idea.
    Namespaces are one honking great idea -- let's do more of those!

Tuesday, June 4, 2013

Python : PygLatin


pyg = 'ay'

original = raw_input('Enter a word:')
word = original.lower()
first = original[0]
new_word = word + pyg

if len(original) > 0 and original.isalpha():
    if first == "a" or first == "e" or first == "i" or first == "o" or first == "u":
        print 'vowel'
    else:
        new_word = original[1:] + original[0:1] + pyg
        print new_word
else:
    print 'empty'
 
 
 

Monday, June 3, 2013

J.S. Project: Building a Cash Register


// Here is my final J.S. Project before I move on to Python: 

function StaffMember(name,discountPercent){
    this.name = name;
    this.discountPercent = discountPercent;
}

var sally = new StaffMember("Sally",5);
var bob = new StaffMember("Bob",10);

// Create yourself again as 'me' with a staff discount of 20%
var me = new StaffMember("Jenny",20);

var cashRegister = {
    total:0,
    lastTransactionAmount: 0,
    add: function(itemCost){
        this.total += (itemCost || 0);
        this.lastTransactionAmount = itemCost;
    },
    scan: function(item,quantity){
        switch (item){
        case "eggs": this.add(0.98 * quantity); break;
        case "milk": this.add(1.23 * quantity); break;
        case "magazine": this.add(4.99 * quantity); break;
        case "chocolate": this.add(0.45 * quantity); break;
        }
        return true;
    },
    voidLastTransaction : function(){
        this.total -= this.lastTransactionAmount;
        this.lastTransactionAmount = 0;
    },
    // Create a new method applyStaffDiscount here
    applyStaffDiscount: function(employee){
        this.total -= (this.total*(employee.discountPercent/100));
    }
    
};

cashRegister.scan('eggs',1);
cashRegister.scan('milk',1);
cashRegister.scan('magazine',3);
// Apply your staff discount by passing the 'me' object 
// to applyStaffDiscount
cashRegister.applyStaffDiscount(me);

// Show the total bill
console.log('Your bill is '+cashRegister.total.toFixed(2));

Saturday, May 25, 2013

What Would You Like to Eat Today?


Oh man, it is so totally freeing not having to create those stale blog posts! Here are two more mini -games micro-games I whipped up later in the week. They're both related to food (no surprise, right?) and I think I'm really getting to master the whole choose-your-adventure-game-mode. I think it would be relatively achievable to write a storybook and have several different possible endings! How cool would that be? I also found out that it's actually pretty useful to create diagrams in a notebook before starting to code everything out. It's like drafting an essay or creating a plan so that everything makes sense and you don't have to waste time figuring those silly little details out. Ah, this is so much better and way more engaging! I hope you all give these games a try!

// here's my first version: 

var omelette = prompt("Good morning! Are you hungry for breakfast? The chickens and ducks laid a whole bunch of eggs, so we're planning to make omelettes for everyone. Do you eat meat?").toUpperCase();

switch(omelette) {
  case 'YES':
    var salmon = prompt("Do you eat fish?").toUpperCase();
    if(salmon === 'YES') {
      console.log("One smoked salmon and tomato omelette coming right up!");
    } else {
      console.log("We'll have your ham and cheese omelette plated in a jiffy!");
    }
    break;
  case 'NO':
      var dairy = prompt("Do you eat dairy?").toUpperCase();
    if(dairy === 'YES') {
      console.log("Well here's a cheesy mushroom and onion omelette... one of my favorites!");
    } else {
      console.log("Sorry, we don't have any omelettes for you!");
    }
    break;
  default:
    console.log("Say you don't like omelettes? Well we have some soggy oatmeal leftover from yesterday's brunch...");
}
     

// here's the second (and slightly more intricate) one: 

var hungry = prompt("So I see you're feeling a little hungry. Well, what time is it (BREAKFAST, LUNCH, or DINNER time)?").toUpperCase();

switch(hungry) {
  case 'BREAKFAST':
    var meat_breakfast = prompt("It's breakfast time! Do you eat meat?").toUpperCase();
    var dairy_breakfast = prompt("Do you eat dairy?").toUpperCase();
    if(meat_breakfast === 'YES' && dairy_breakfast === 'YES') {
      console.log("Have some bacon and eggs!");
    } else if(meat_breakfast === 'YES' && dairy_breakfast === 'NO') {
      console.log("Allergic to dairy? How about some sausage and hashbrowns?");
    } else if(meat_breakfast === 'NO' && dairy_breakfast === 'YES') {
      console.log("What about a tomato and spinach omelette?");
    } else {
      console.log("How about some fresh fruit?");
    }
    break;
  case 'LUNCH':
    var meat_lunch = prompt("Lunchtime! Do you eat meat?").toUpperCase();
    var dairy_lunch = prompt("What about dairy? Can you have milk? Eggs?").toUpperCase();
    if(meat_lunch === 'YES' && dairy_lunch === 'YES') {
      console.log("Alrighty, how about a ham and cheese sandwich? Does that sound good to you?");
    } else if(meat_lunch === 'YES' && dairy_lunch === 'NO') {
      console.log("Well what about just a tunafish sandwich?");
    } else if(meat_lunch === 'NO' && dairy_lunch === 'YES') {
      console.log("Grilled cheese for one! Coming right up!");
    } else {
      console.log("What about a classic PB and J sandwich? Does that sound good to you?");
    }
    break;
  case 'DINNER':
    var meat_dinner = prompt("Ah, the last and BEST meal of the day! Do you include meat in your diet?").toUpperCase();
    var dairy_dinner = prompt("How about dairy?").toUpperCase();
    if(meat_dinner === 'YES' && dairy_dinner === 'YES') {
      console.log("What about some pepperoni pizza?");
    } else if(meat_dinner === 'YES' && dairy_dinner === 'NO') {
      console.log("How about the classic spaghetti and meatballs? We'll hold the cheese, don't worry about that!");
    } else if(meat_dinner === 'NO' && dairy_dinner === 'YES') {
      console.log("In the mood for mac and cheese! I know I am!");
    } else {
      console.log("Well in that case, what about a nice refreshing kale salad?");
    }
    break;
  default:
    console.log("Hmm... you sure you're hungry?");
}


P.S. I started using canv.as and it is so freaking fun. Here's my page.

ZOMBIE SUSHI ATTACK


I originally wanted to blog about another assignment from Codeacademy and title it J.S. Project : Choose Your Own Adventure Part 2!  I had even planned to mimic the same written format--which had set the tone in all the twenty posts preceding this one. Even though this formulaic composition had initially seemed effective in helping me review all the new concepts, the procedure quickly became a drag and I soon felt like blogging these assignments became more of a drudgery than a fun way to imbibe all this new material. 

However I was determined to continue this habit, perhaps subconsciously fearing that if I stopped posting on a semi-regular basis, it would seem like I wasn't really making much progress. I measured my progress to the number of posts I churned out--whether or not the quality of content each had possessed. This once interactive learning method soon became a mindless conversion of text from one window to another and I was fooling myself, until Monday... when I couldn't find my keys. You see, during the day I am the only person at home so not being able to locate my keys essentially means, not being able to go outside. Frustrated that I couldn't go on my daily jog or run by the local grocery store to grab some food, I was stuck here... Trapped... With this pain of this assignment looming over my head. So I bit the bullet and took a look at this one assignment and decided to give it a go...NOT thinking about this blog, NOT thinking about putting the instructor's words into my own and creating a teaching post, but to just work directly with the code itself. A few days ago, I stumbled upon this "open source collaborative web development debugging tool" and it was the key to my problem! I studied the code provided from Codeacademy and wrote my own--incorporating my adventures of working at a hostess at a sushi bar. 

This is my code, and you can even demo it right here

var zombie_sushi = prompt("OH NO! The bucket of plutonium got all over the sushi and now they've turned into brain-craving zombies! Do you SLAY them, EAT them, or RUN?").toUpperCase(); 

switch(zombie_sushi) {
  case 'SLAY': 
    var macho = prompt("So, you consider yourself macho? (YES or NO)?").toUpperCase(); 
    var buff = prompt("Let's see if those burpees did anything to your level of fitness! You think you're ready?").toUpperCase();
    if(macho === 'YES' || buff === 'YES') {
      console.log("You only need one of the two! You massacred all the zombie sushi! Good job, bro!");
    } else {
      console.log("You're not macho OR buff? Sucks for you, probably should have worked on those squats a little more. You died!");
    }
    break; 
  case 'EAT': 
    var soy_sauce = prompt("All right, I guess you can try to defeat them this way... Eeeurgh. Got your soy sauce packets (YES or NO)?").toUpperCase(); 
    var wasabi = prompt("Hold on a minute, dude. You've got your green glob of wasabi with you, right?").toUpperCase(); 
    if(soy_sauce === 'YES' && wasabi === 'YES') {
      console.log("Woohoo! You've defeated the zombie sushi, hopefully you won't get a bellyache later on!"); 
    } else { 
      console.log("Dang! You can only use the magical combination of soy sauce and wasabi together! Not on their own. Sorry man, but you're dead!");
    }
    break;
  case 'RUN': 
    var speedy = prompt("Come on, let's get a move on! You're fast, right?").toUpperCase(); 
    var rollerblades = prompt("Wait, you have rollerblades in your backpack?").toUpperCase(); 
    if(speedy === 'YES' || rollerblades === 'YES') {
      console.log("Bam, you got away! You live to see another glimpse of the sunlight.");
    } else {
      console.log("Oh no, you're too slow and you didn't have your rollerblades in your bag? Sorry man, but you're a goner.");
    }
    break;
  default:
    console.log("Woah, bro. Didn't understand what you said. Hit Run and try again, this time picking SLAY, EAT, or RUN!");
}

/* I know it's short, but it's a start. And I had a whole lot of fun writing this--even though it's pretty nonsensical... but who cares. Maybe I'll animate it someday? */

I think from now on, I'm going to stray away from the previous formulaic and boring method I've used to craft my post and focus on something a little more creative and thoughtful. It's way more fun and I hope you enjoy!

Monday, May 20, 2013

J.S. Project: Dragon Slayer



We'll be combining while loops with some other control statements (like if / else statements) to create a dragon slaying minigame.

01 / 04 : Let's first start off by declaring the variables which we'll be using. We're going to need a variable to check if we're still slaying, a variable to check if we hit the dragon, a variable to keep track of how much damage we've dealt the dragon this round, and a variable to keep track of total damage. We'll also be relying on random numbers to see if we hit the dragon, and if so, how much damage we did. JavaScript generates random numbers like this:
    var randomNumber = Math.random();
This creates a random number between 0 and 1. By multiplying the number and rounding it down, we can make it a random whole number. For example:
    Math.floor(Math.random() * 5 + 1);
will generate a random number between 1 and 5 inclusive. Now let's declare and set the following variables:
    1. slaying equal to true
    2. youHit to a random number that's either 0 (which JavaScript reads as 'false') or 1 {which JavaScript reads as 'true')
    3. damageThisRound to a random number between 1 and 5 (inclusive)
    4. totalDamage to 0
    HINT - by multiplying the random number (which is between 0 and 1) by 5, we make it a random number between 0 and 5 (for example, 3.1841). Math.floor() rounds this number down to a whole number, and adding 1 and the end changes the range from between 0 and 4 to between 1 and 5 (up to and including 5).

var slaying = true;
var youHit = Math.random();
var damageThisRound = Math.floor(Math.random() * 5 + 1);
var totalDamage = 0;

02 / 04 : Wonderful. Now let's add in our while loop. We want to run this whole game as long as we're trying to kill the dragon--that is, while slaying is true. When checking variables like slaying that are set to true, we don't need to write something like this:
    while(slaying === true)
Instead, we can just write:
    while(slaying)
Now let's create a while loop that only executes when slaying is true. For this exercise, set slaying to false in the body of the loop (we want to make sure the loop can exit... no infinite loops for us!) 

var slaying = true;
while(slaying) {
    slaying = false;
}

03 / 04 : Now time to add a couple of branches to our program so it can handle different outcomes. You know what this means... if and else! Inside the while loop, create an if / else statement that checks the value of youHit. If it's 1 (true), it should log a congratulatory message to the console, telling the user (s)he hit the dragon. If it's 0 (false), it should log a message to the console saying that the dragon defeated you. Either way, slaying should be set to false, since either you beat the dragon (and the slaying's over) or the dragon beat you!

while(slaying) {
    if (youHit) {
        console.log("You hit!");
    } else {
        console.log("You missed!");
    }
    slaying = false;
}

04 / 04 : We're gonna add the second 'if' statement. In the first branch of our if statement (right after the console.log() where we congratulate the player for hitting the dragon), let's set totalDamage equal to totalDamage + damageThisRound. The shortcut for this is: the += operator. When you type
    totalDamage += damageThisRound 
you're telling JavaScript to add totalDamage and damageThisRound together, then assign the new value to totalDamage. Inside the first if statement, create a second if statement that checks to see if totalDamage is greater than or equal to 4. If so, it should log to the console that the player slew the dragon and set slaying equal to false (since the dragon's dead, the slaying is over). If totalDamage isn't greater than or equal to 4, youHit should be assigned a new random 1 or 0. (This is as easy as setting youHit to the same expression you used when you first declared it.)


while(slaying) {
    if (youHit) {
        console.log("You hit!");
        totalDamage += damageThisRound;
            if ( totalDamage >= 4) {
                console.log("You win!");
                slaying = false
            } else { 
                youHit = Math.floor(Math.random()*2);
            }
    } else {
        console.log("You missed!");
        slaying = false;
    }
}


You did it! You've written your own dragon slaying game!

Wednesday, May 15, 2013

J.S. Project: Search Text for Your Name



Today, we're going to write a short program that checks a block of text for my name. More specifically, it's going to check for the first letter of my name, then push (add) the number of characters equal to my name's length to an array. By inspecting the array, we'll be able to see if our name was mentioned.

/*jshint multistr:true */
text = "Blah blah blah blah blah blah blah blah Jenny blah \
blah blah blah blah blah blah Jenny blah blah blah blah \
blah blah blah blah blah blah blah blah blah Jenny";

var myName = "Jenny";
var hits = [];

// Look for "J" in the text
for(var i = 0; i < text.length; i++) {
    if (text[i] === "J) {
        // If we find it, add characters up to
        // the length of my name to the array
        for(var j = i; j < (myName.length + i) ; j++) {
            hits.push(text[j]);
        }
    }
}

if (hits.length === 0) {
    console.log("Your name wasn't found!");
} else {
    console.log(hits);
}

01 / 05 : Let's start by declaring our variables: text, myName, and hits. Since text could be quite long, try putting a blackslash (\) at the end of each line to make our string "wrap" to the next line of the editor. We can ignore the /*jshint multistr:true */ for now because all it does is tell the console to stop worrying about our use of backslash characters for wrapping long lines of text. Now set the following three variables:
1. text, and make a string containing some text
2. myName, and make a string containing just your name
3. hits, and make it an empty array
    HINT - make an empty array by setting your variable equal to [] (an array with nothing in it)

var text = "blah blah Jenny blah blah blah Jenny blah";
var myName = "Jenny";
var hits = [];

02 / 05 : Let's write our outer for loop. Below our existing code, create a for loop that starts at 0, continues until it reaches the end of text, and increments by 1 each time. (Meaning it will check each character in the string).
    HINT - Remember the syntax for a for loop looks like this:
        for(var i = 0; i < condition; i++) {
            // Do something !
        }
    In place of "condition", put the condition that will stop the loop from running. In this case, our  
    condition should be less text.length.

for(var i = 0; i < text.length; i++) {

}

03 / 05 : Nice! Now let's move on to the if statement. We'll want to place the if statement inside our for loop to make sure the program checks the if statement each time it moves forward through the loop. Essentially, the for loop is saying: "Hey program! Go through every letter in 'text'." The if statement will say: if you see something interesting, push that text into an array!" You can treat a string like an array of characters: For instance, you know that
        var myArray = ['hello', 'world'];
        myArray[0]; // equals 'hello'
But this also works on strings!
        var myName = 'Jenny';
        myName[0] // equals 'J'
Add your if statement in the body of your for loop and it should check to see whether the curent letter is equal to the first letter of your name.
    HINT - Remember, an if statement looks like thisis:
        if (some condition) {
            // Do something!
        }

    You can check the i th letter of text like so: \
    // Assuming your name starts with 'E'
    if (text[i] === 'E') {
        // Do something!
    }

for (var i = 0; i < text.length; i++){
    if (text[i] === 'J') {
 
    }
}

04 / 05 : Now time to add your second "for" loop. You're going to write it inside the body of your first if statement (between the if's {}s). This loop is going to make sure each character of your name gets pushed to the final array. The if statement says: "If we find the first letter of your name, start the second for loop!" This loop says: "I'm going to add characters to the array until I hit the length of the user's name." So if your name is 11 letters long, your loop should add 11 characters to hits if it ever sees the first letter of myName in text. We'll want to set our second loop's iterator to start at the first one, so it picks up where that one left off. If our first loop starts with
    for(var i = 0; // rest of loop setup
our second loop should be something like
    for(var j = i; // rest of loop setup
In the body of our loop, have our program use the .push() method of hits. Just like strings and arrays have a .length method, arrays have a .push() method that adds the thing between parentheses to the end of the array, for example:
    newArray = [];
    newArray.push('hello');
    newArray[0] // equals 'hello'
    HINT - the loop should stop when it hits the value of the first iterator plus the length of the myName
    variable.

for(var i = 00; i < text.length; i++){
    if (text[i] === 'J') {
        for(var j = i; j < (myName.length + i); j++){
            hits.push(text[j]);
        }
    }
}

05 / 05 : You've now got the engine of your search program running! It's going to:
    1. loop through the array
    2. compare each letter to the first letter of your name, and if it sees that letter:
    3. it will push that letter and all the letters that follow it to an array, stopping when the number of
        letters it pushes are equal to the number of letters in your name.
So under your existing code (and outside all your other loops!) Set up an if / else statement. If you don't have any hits, log "Your name wasn't found!" to the console. Otherwise, log the hits array to the console.

if (hits.length === 0) {
    console.log("Your name wasn't found!");
} else {
    console.log(hits);
}

** Unfortunately, this system isn't perfect. For instance, if the paragraph contains both "Jenny" and "Jerry", we'll see this in our hits array:
['J', 'e', 'n', 'n', 'y', 'J', 'e', 'r', 'r', 'y']

Friday, May 3, 2013

Javascript: Review of Functions


// Introducing Functions 

A function can be defined by preceding a bunch of code with the word function followed by its inputs. These inputs are known as parameters and are enclosed with (). The associated code is enclosed with {}.

// Accepts a number x as input and returns its square
var square = function(x) {
    return x * x;
};

// Accepts a number x as input and returns its cube
var cube = function(x) {
    return x * x * x;
};

cube(7);

// Understanding Parameters
Functions can have zero, one, or more parameters. You can think of these as input that the function receives, and then uses to do something.

// the code example shows a function that takes two number as arguments and returns their product
var multiply = function (x, y) {
    return x * y;
};

multiply(2, 5);

// Argument Types, part 1
We just saw that the naming of parameters doesn't impact the caller of a function. In JavaScript, you don't need to specify a type when defining a function which means that when someone else calls your function, they can supply any type of argument that they want to-- a number, a string, an array, etc. This may lead to some strange behavior if you call your multiply function with a string:

multiply("tweedledee", "tweedledum");
// returned value is NaN (stands for, not a number)

// Argument Types, part 2
Let's say that we want to make sure that the caller always gets a numeric value back, even if the input wasn't of the right type... To achieve that, we need to check the type of argument that was passed in. If it wasn't a number, we probably shouldn't try to multiply it. We'll just return 0 in that case.

var cube = function (x) {
    if (typeof(x) !== 'number') return 0;
    return x * x * x;
};

// the cube() function should return 0.
cube("test");

// Local Variables
Each parameter of a function is effectively a variable. It has a name that we can use inside the function to refer to the value that was supplied by the call to the function. Once the function has been called, is that name available outside the function? To test this, let's run the code below as is:

var volume = function (w, l, h) {
    return w * l * h;
};

volume(2, 3, 4) ;
console.log(w);

We get a "Reference: Error", w is not defined. What that means is that the name w was set to the value 2 inside the function when it was called, but was never defined outside of the function. For the code to work, we've got to set:

var w = 15;

What if you need additional local variables beyond the arguments (e.g. to hold an intermediate result)? In the volume function, you can see an example of such a local variable. The variable area is local because it is visible only inside the function. Even after the function has been called, area is still not defining outside the function and referring to it triggers an error.

var volume = function (w, l, h) {
    var area = w * l;
    return area * h;
};

// var area = 36
console.log("Inside the function, area is 6");
console.log("The volume is " + volume(2, 3, 4));
console.log("Outside the function, area is " + area);

You'll get another Reference Error: area is not defined... so now, uncomment line 6 and you'll have:
Inside the function, the area is 6
The volume is 24
Outside the function, area is 36

Now you see a slightly different version of the volume function: can you spot the difference?


var area = 36;
var volume = function (w, l, h) {
    area = w * l;
    return area * h;
};

console.log(volume(2, 3, 4));
console.log(area);


Area is no longer preceded by var. The area variable is no longer local to the function. Instead, when the function has been called, the area is set to 2 * 3 = 6 when volume is called. The area variable outside the function is called a global variable because it is visible everywhere. Modifying it inside a function is referred to as a side-effect and is generally something you want to avoid. This is why you should always use var when declaring variables!

var area = 36;
var volume = function (w, l, h) {
    var area = w * l;
    return area * h;
};

console.log(volume(2, 3, 4));
console.log(area);

Wednesday, May 1, 2013

J.S. Project: Rock, Paper, Scissors


Today, we're going to create the classic rock paper scissors game! Each player chooses either rock, paper, or scissors and the possible outcomes are:

Rock destroys scissors.
Scissors cut paper.
Paper covers rock.

Our code will break the game into three components:
a. User makes a choice
b. Computer makes a choice
c. A compare function will determine who wins

We are going to first start off by asking the user which option they'd like to pick. We're going to use this choice later in the compare function to determine the winner.

01 / 07 : declare a variable called userChoice and set it equal to the answer we get by asking the user: "Do you choose rock, paper, or scissors?":
    HINT - remember to prompt the user to ask a question...

var userChoice = prompt("Do you choose rock, paper, or scissors?");

02 / 07 : Awesome sauce! Now, we've gotta get the computer to make a choice too. The game is going to be fun (and worth playing) if the computer chooses randomly. If we declare a variable and set it equal to Math.random(), that variable will equal a number between 0 and 1. Declare a variable called computerChoice and set it equal to Math.random(). Then, print out computerChoice so you can see how Math.random() works!

var computerChoice = Math.random();
console.log(computerChoice);

03 / 07 : So we've created computerChoice but it now equals a random number between 0 and 1. We need to somehow translate this random number into a random choice of rock, paper, or scissors:
    1. If computerChoice is between 0 and 0.33, make computerChoice equal to rock.
    2. If computerChoice is between 0.34 and 0.66, make computerChoice equal to paper.
    3. If computerChoice is between 0.67 and 0.99, make computerChoice equal to scissors.
We've gotta use if / else if / else because there are three outcomes (we use if / else for two):

if ( 0 <= computerChoice <=  0.33 ) {
    console.log("rock");
} else if ( 0.34 <=  computerChoice <=  0.66 ) {
    console.log("paper");
} else {
    console.log("scissors");
}

04 / 07 : Now comes the fun part! We're going to create a function that takes two parameters (the two choices made) and return the winning choice. We have to first figure out all the different outcomes, which are essentially the choices that the user makes equaling the choice the computer makes. Declare a  function called compare() taking two parameters choice1 and choice2. Inside the function, write an if statement such that if the two parameters equal each other, the function will return: "The result is a tie!".

function compare(choice1, choice2) {
    if (choice1 === choice2) {
        return("The result is a tie!");
    }
}

05 / 07 : Wonderful. Now, let's consider the other scenarios in this game: what if choice1 is "rock"? Given choice1 is "rock",
        a. if choice2 is "scissors", then "rock" wins.
        b. if choice2 is "paper", then "paper" wins.
How are we going to structure this? Well, we've already got an if statement, so the code inside that if statement will be another if statement itself! Write an if statement where the condition is choice1 equals "rock". Then, in the code block for that if statement, write an if / else statement. In that statement, if choice2 is "scissors", return "rock wins". Otherwise, return "paper wins".
    HINT - putting if statements inside if statements might be a little tricky at first. Here's an outline of what the syntax should look like:
if (condition) {
    if (condition) {
        return "some string";
    } else {
        return "some other string";
    }
}

if (choice1 === "rock") {
    if (choice2 === "scissors") {
        return("rock wins");
    } else {
        return("paper wins");
    }
}  

06 / 07 : Well, what if choice1 is "paper"?
        a. if choice2 is "rock", then "paper" wins.
        b. if choice2 is "scissors", then "scissors" wins.
We're gonna use the same structure to add these two extra scenarios:

if (choice1 === "paper") {
    if (choice2 === "rock") {
        return("paper wins");
    } else {
        return("scissors wins");
    }
 }

07 / 07 : Lastly, we've got to consider what if choice1 s "scissors:
        a. if choice2 is "rock", then "rock" wins.
        b. if choice2 is "paper", then "scissors" wins.
We're almost done, let's take the same structure we've used in the past couple exercises and apply it to these two new scenarios:

if (choice1 === "scissors") {
    if (choice2 === "rock") {
        return("paper wins");
    } else {
        return("scissors wins");
    }
}
     
Finally, call your function and pass in userChoice and computerChoice as your two parameters:

compare(userChoice, computerChoice);

// now, here's the entire game all in one go: 


var userChoice = prompt("Do you choose rock, paper or scissors?");

var computerChoice = Math.random();
if (computerChoice < 0.34) {
    computerChoice = "rock";
} else if(computerChoice <= 0.67) {
computerChoice = "paper";
else {
computerChoice = "scissors";
}

function compare( choice1, choice2 ) {
    if (choice1 === choice2 ) {
        return("The result is a tie!");
    }
   
    if (choice1 === "rock") {
        if (choice2 === "scissors") {
            return("rock wins");
        } else {
            return("paper wins");
        }
    }
   
    if (choice1 === "paper") {
        if (choice2 === "rock") {
            return("paper wins");
        } else {
            return("scissors wins");
        }
    }
   
    if (choice1 === "scissors") {
        if (choice2 === "rock") {
            return("rock wins");
        } else {
            return("scissors wins");
        }
    }
}

compare(userChoice, computerChoice);


Congrats on making your awesome game!

P.S. Check out my new video where I give you all a tour of my room

Song of the day // The Hours (Beach House) 

Saturday, April 27, 2013

J.S. Project: Choose Your Own Adventure! (Continued)


Here is my really lame and micro version of the choose-your-own-adventure game. It was inspired by this.

confirm("Ready to play this awesome game?");

var age = prompt("How old are you?");
    if (age > 18) {
        console.log("OK, you're allowed to play, but I'm not responsible for anything that goes wrong.");
    } else {
        console.log("Alllllright. Let's get on with the show, shall we?");
    }
 
// intro
console.log("You are a sloth in the middle of the rainforest. Your goal is to stay alive. Let the first trial begin");

console.log("You feel the sudden urge to use the bathroom.");

var userAnswer1 = prompt("Will you climb down from the safety of your tree to relieve yourself?");
if (userAnswer1 === "yes") {
    console.log("Oh no! A sunbear just appeared from out of nowhere! It seems like you're going to end up for dinner! Uh oh.");
} else {
    console.log("Oops. You just peed all over yourself. Gross.");
}

// feedback
var feedback = prompt("How was the game? I know it was a bit short, but please rate it from 1 - 10!");
if (feedback > 8) {
    console.log("So glad you liked it! Stay tuned for more!");
} else {
    console.log("Boo. You poop.");
}


P.S. Here's a vlog I created today! I'd totally appreciate it if you check it out!! :) 

Friday, April 26, 2013

J.S. Project: Choose Your Own Adventure!


Today, we're going to create a 'choose your own adventure' game. Exciting, right? It will have a basic story line, the opportunity for the user to make a couple of decisions, and a happy ending (hopefully).

01 / 07 : Let's use the confirm command to ask your user if they are ready to play.
    HINT - remember, to get the user to confirm something, the syntax looks like this:
        confirm("I understand confirm!");

// Check if the user is ready to play!
confirm("Are you ready to embark on this adventure of fun?");


02 / 07 : However before we start playing, we're going to check to see if the user is old enough to play! This step involves two bits of code. Declare a variable age using prompt. Make that age equal to the answer you prompt the user to give (ie. ask the user 'how old are you?'). Finally, create an if / else statement: if the user is less than 19, use console.log and tel the that they're allowed to play but you take no responsibility. Else, use console.log and give them an encouraging message to play on!
    HINT - recall the syntax for if / else statements:
        if (condition) {
            code code code;
        } else {
            code code code;
        }

var age = prompt("How old are you?");
    if (age < 18) {
        console.log("You're allowed to play, but I take no responsibility.");
    } else {
        console.log("Well, what are you waiting for? Let's get started already!");
    }


03 / 07 : We've gotta set up the scene for our story. Here's a short little introduction that we can use for now: Snow White and Batman were hanging out at the bus stop, waiting to go to the shops. There was a sale on and both needed some new threads. You've never really liked Batman. You walk up to him.
Let's print the intro using console.log. The intro is full of words... remember how words are called 'strings' in JavaScript? Don't forget how to properly use strings!
    HINT - don't forget to put quotes around the intro!

// introduction
console.log("Snow White and Batman were hanging out at the bus stop, waiting to go to the shops. There was a sale on and both needed some new threads. You've never really liked Batman. You walk up to him.");


04 / 07 : Our story is ready to move along! There's a scene and your user is about to talk to batman. Under your existing code, print out the storyline: "Batman glares at you." Then declare a variable userAnswer and make it equal a prompt that asks the user "Are you feeling lucky, punk?" (This will be the question that Batman asks your user).

console.log("Batman glares at you.");
var userAnswer = prompt("Are you feeling lucky, punk?");


05 / 07 : Now we've gotta create different scenarios using the if / else statements! Use an if / else statement to write out the last part of this game. If userAnswer is "yes", print out: "Batman hits you very hard. It's Batman and you're you! Of course Batman wins!" Otherwise, print out: "You did not say yes to feeling lucky. Good choice! You are a winner in the game of not getting beaten up by Batman."
    HINT - Remember: = is for assignment, and === is to check this are equal!

if (userAnswer === "yes") {
    console.log("Batman hits you very hard. It's Batman and you're you! Of course Batman wins!");
} else {
    console.log "You did not say yes to feeling lucky. Good choice! You are a winner in the game of not getting beaten up by Batman.");
}


06 / 07 : It's probably worthwhile to ask your user for feedback. Let's create a variable called feedback and prompt the user to rate your game out of 10. If the score is greater than 8, print out: "This is just the beginning of my game empire. Stay tuned for more!" Otherwise, print out: "I slaved away at this game and you gave me that score?! The nerve! Just you wait!"
    HINT - var feedback  = prompt("Message");

var feedback = prompt("Could you rate my game out of 10?");
    if (feedback > 8) {
        console.log("This is just the beginning of my game empire. Stay tuned for more!");
    } else {
        console.log("I slaved away at this game and you gave me that score?! The nerve! Just you wait!");
    }


07 / 07 : Congrats! You've just programmed your first game! Now it's your turn to program your own 'choose your own aventure game'.






Thursday, April 25, 2013

Javascript: Objects II in Review


01/ 04
Instructions: Examine the languages object. Three properties are strings, whereas one is a number. Use a for-in loop to print out the three ways to say hello. In the loop, you should check to see if the property value is a string so you don't accidentally print a number.
    HINT: Use an if statement in combination with the typeof operator to figure out whether or not something is a "string". If it's a "string", then print it!

Make sure you're checking the property value (e.g., "Hello!") and no the property name (e.g., english). Recall that if we save a property name to a variable, we can access the value associated with that name using bracket notation.

Recall the for-in loop:

for(var x in obj) {
executeSomething();
}

/* This will go through all properties of obj one by one and assign the property name on each run of the loop. */

var languages = {
    english: "Hello!",
    french: "Bonjour!",
    notALanguage: 4,
    spanish: "Hola!"
};

// print hello in the 3 different languages
for(var x in languages) {
if (typeof languages[x]);
}
}

02/ 04
Instructions: Add the sayHello method to the Dog class by extending its prototype. sayHello should print to the console: "Hello this is a [breed] dog", where [breed] is the dog's breed.
    HINT: recall how we previously added a method to the Dog class:
Dog.prototype.bark = function()
{
    console.log("Woof");
}; 

To access a dog's breed from within the method, use this.breed.

function Dog (breed) {
    this.breed = breed;
};

// add the sayHello method to the Dog class
// so all dogs now can say hello
Dog.prototype.sayHello = function()
{
    console.log("Hello this is a " + this.breed + " dog");
};

var yourDog = new Dog("golden retriever");
yourDog.sayHello();

var myDog = new Dog("dachshund");
myDog.sayHello();

03/ 04 
Instructions: Let's first see what type Object.prototype is. Do this in line 2 and save it into prototypeType. If all goes well, you should realize that Object.prototype itself is an object! And since all objects have the hasOwnProperty method, it's pretty easy to check if hasOwnProperty comes from Object.prototype.
    HINT: to see what type Object.prototype is, we should use typeof Object.prototype. The property we want to check for is actually "hasOwnProperty", so line 6 should look like: Object.prototype.hasOwnProperty("hasOwnProperty").

// what is this "Object.prototype" anyway...?
var prototypeType = typeof Object.prototype; 
console.log(prototypeType);

// now let's examine it!
var hasOwn = Object.prototype.hasOwnProperty("hasOwnProperty"); 
console.log(hasOwn);

04/ 04 
Instructions: Modify the StudentReport class so that no grades will be printed to the console in the for-in loop. However, getGPA should still function properly in the last line.
    HINT: You should be changing public variables ( this.grade ) to private variables ( var grade ). If we want to getGPA to be able to be called from outside this class, should we change it to be private? You should find yourself needing to modify getGPA itself. this.grade1 will not be available if you did not declare it previously.

function StudentReport() {
    var grade1 = 4;
    var grade2 = 2;
    var grade3 = 1;
    this.getGPA = function() {
        return ( grade1 + grade2 + grade3 ) / 3;
    };
}

var myStudentReport = new StudentReport();

for(var x in myStudentReport) {
    if(typeof myStudentReport[x] !== "function") {
        console.log("Muahaha! "+myStudentReport[x]);
    }
}

console.log("Your overall GPA is "+myStudentReport.getGPA());







Tuesday, April 23, 2013

Javascript: Private and Public


All properties in JavaScript are automatically public, which means that they can be accessed outside of the class. Look at the Person class below. It has three properties: firstName, lastName, and age. Think of these properties as the information a class is willing to share.

 On lines 8 and 9, we access the firstName and lastName properties of john and assign them myFirst and myLast. Note that we are free to access the firstName, lastName, and age properties, which is what we mean when we say that they are public.

function Person(first, last, age) {
    this.firstName = first;
    this.lastName = last;
    this.age = age;
}

var john = new Person( 'John', 'Doe', 30);
var myFirst = john.firstName;
var myLast = john.lastName;
var myAge = john.age;

Yay! But what if an object wants to keep some information hidden? Remember local variables? (--They can only be accessed from within that function!) Well functions can also have private variables which are pieces of information that can only be directly accessed from within the class.

Here, the Person class has been modified to have a private variable called bankBalance. Notice that it looks just like a normal variable except that it is defined inside the constructor for Person, without using this, but instead using var. This makes bankBalance a private variable.


function Person(first, last, age) {
    this.firstName = first;
    this.lastName = last;
    this.age = age;
    var bankBalance = 7500;
}


We we try to print his bankBalance out, all we get is undefined.

Methods can also be private within a class and inaccessible outside of the class. Changing this.returnBalance from the last exercise to var returnBalance makes this method private. The way to access a private method is similar to accessing a private variable. You must create a public method for the class that returns the private method.

var returnBalance = function() {
    return bankBalance;
};
this.askTeller = function() {
    return returnBalance;
};

var john = new Person('John', 'Doe', 30);
console.log(john.returnBalance);
var myBalanceMethod = john.askTeller();
var myBalance = myBalanceMethod();
console.log(myBalance);

The askTeller function has been modified within the Person class to directly give you your balance. However, it now needs the account password parameter in order to return the bankBalance.


function Person(first,last,age) {
   this.firstname = first;
   this.lastname = last;
   this.age = age;
   var bankBalance = 7500;
 
   this.askTeller = function(pass) {
     if (pass == 1234) {
        return bankBalance;
     }
     else {
        return "Wrong password.";
        }
   };
 
   var myBalance = function(pass) {
       return askTeller;
   };
}

var john = new Person('John','Doe',30);
/* the variable myBalance should access askTeller() with a password as an argument  */

Sunday, April 21, 2013

Javascript: Inheritance in Object Oriented Programming


Inheritance allows one class to see and use the methods and properties of another class. Let's create a class called Animal, along with a sayName method:

function Animal(name, numLegs) {
    this.name  = name;
    this.numLegs = numLegs;
};

animal.prototype.sayName = function()
{
    console.log("Hi my name is " + this.name)
};

// here's a code to test the above constructor and method
var penguin = new Animal("Captain Cook", 2);
penguin.sayName();

Wouldn't it be cool if we created a Penguin class? Let's do that so that we can give it some methods unique only to a penguin and not confuse it with the Animal class.

function Penguin(name, numLegs) {
    this.name = name;
    this.numLegs = numLegs;
}

Penguin.prototype.sayName = function()
{
    console.log("Hi my name is " + this.name);
};

We seemed to have reused a lot of the same code as the Animal class. This goes against the "DRY" principle--aka "don't repeat yourself"! We're going to create a new Penguin class, but we're going only take a name parameter, and within the constructor itself, set this.numLegs to 2.

function Penguin (name) {
    this.name = name;
    this.numLegs = 2

// set its prototype to be a new instance of Animal
Penguin.prototype = new Animal();

Now we're going to create an Emperor class that takes a single name parameter and sets its name property to be this value.

// create your Emperor class and make it inherit from Penguin
function Emperor (name) {
    this.name = name;
}

Emperor.prototype = new Penguin();
// create an "emperor" object and print the number of legs it has
var emperor = new Emperor("Mr. McWaddle");
console.log(emperor.numLegs);

The "prototype chain" in Javascript sort of like a food chain. If JavaScript encounters something it can't find it the current class's methods or properties, it looks up the prototype chain to see if it's defined in a class that it inherits from. This keeps going upwards until it stops all the way at the top: the Object.prototype. All classes inherit directly from Object, unless we change the class's prototype.

// original classes
function Animal(name, numLegs) {
    this.name = name;
    this.numLegs = numLegs;
    this.isAlive = true;
}
function Penguin(name)
    this.name = name;
    this.numLegs = 2;
}
function Emperor(name) {
    this.name = name;
    this.saying = "Waddle waddle";
}

// set up the prototype chain
Penguin.prototype = name Animal();
Emperor.prototype = new Penguin();

var myEmperor = new Emperor("Jules");

console.log( myEmperor.saying ); // should print "Waddle waddle"
console.log( myEmperor.numLegs ); // should print 2
console.log( myEmperor.isAlive ); // should print true

Saturday, April 20, 2013

Javascript: Object-Oriented Programming Basics


Alright, so now we can finally learn the basics of OOP! The first thing I'm going to introduce is a class.    When you make a constructor, you are actually defining a new class! A class can be thought of as a type, or a category of objects -- remember numbers and strings? Those are types too!

/* take a look at the example below, jenny and alex are two separate objects, but they both belong to the class Person */
function Person(name, age) {
    this.name = name;
    this.age = age;
};

var jenny = new Person("Jenny", 18);
var alex = new Person("Alex", 13);

A prototype keeps track of what a given class can or cannot do. Javascript automatically defines the prototype for class with a constructor.

// for example, this dog constructor ensures that the dog prototype has a breed property
function Dog (breed) {
    this.breed = breed;
};

Classes are really useful because they tell us helpful information about objects. You can actually think of an object as a particular instance of a class. Look at our Person class. We know that any Person will have a  name and age because they are in they are in the constructor. Let's create a function like printPersonName--this will take a Person as an argument and print out their name.

// recall our Person class
function Person(name, age) {
    this.name = name;
    this.age = age;
};

// a function that prints out the name of any given person
function printPersonName(p) {
    console.log(p.name);
};

var jenny = new Person("Jenny", 18);
printPersonName(jenny);

If you want to add a method to a class such that all members of the class can use it, we use the following syntax to extend the prototype:

className.prototype.newMethod = 
function() {
statements; 

}; 

// here's another example using the dog class:
function Dog (breed) {
    this.breed = breed;
};

// here we make fifi and teach her how to bark
var fifi = new Dog("pomeranian");
Dog.prototype.bark = function() {
    console.log("Arf!");
};
fifi.bark();

// here we make maya
var maya = new Dog("Pug");
maya.bark();

P.S. I created a youtube channel where I'll be uploading vlogs and cooking videos and random miscellaneous things, so if you want to get to know me a little better, I suggest you check it out! (And subscribe!) :)

Friday, April 19, 2013

Javascript: Even More on Objects




















How do we figure out if something is an object? We can call typeof thing to figure this out. In general, most types fall under "number", "string", "function", and "object".
var someObject = {someProperty: someValue};
console.log( typeof someObject ); 

// concrete example
var anObj = { job: "I'm an object!" };
console.log( typeof anObj );

Every object in JS comes with some baggage, including a method called hasOwnProperty. This lets us know if an object has a particular property.
// this is how you use hasOwnProperty
var myObj = {
    name: myObj
};

console.log( myObj. hasOwnProperty('name')); // should print true

console.log( myObj. hasOwnProperty('nickname')); // should print false

// here's another example of hasOwnProperty used in an if-else statement: 

/* recall if-else statements: 
if ( expression ) {
} else {
} */

var suitcase = {
    shirt: "Hawaiian"
}; 

if (suitcase.hasOwnProperty("shorts")) {
    console.log(suitcase.shorts); 
} else {
    suitcase.shorts = "red"; 
    console.log(suitcase.shorts);
}

To work with all the properties that belong to an object, let's bring back the for-in loop. 

// define some object 
var pom = {
species: "pomeranian", 
age: 10, 
color: "golden",
};

// for-in loop to print out pom's property names 
for(var property in pom) {
console.log(property); 

We've just learned how to print all of an object's property names with a for-in loop, but how do we print out the values associated with every property?

// for-in loop to print out the value of all pom's properties 

// recall 
pom.species = pom["species"] = "pomeranian" 
// if we say
var x = "species" 
// then
dog[x] = "pomeranian'

for(var x in pom) {
console.log(pom [x]); 

Javascript: Intro to Objects II




















I know we've been reviewing objects I again and again these past couple of blog posts, but I think it's safe to say that there's a reason for this perpetual repetition. Codeacademy really wants you to get down the basics before moving into new territories. Last night I attempted to finish the entire course in one-go--and was almost successful in that endeavor. However, I was stumped by the last lesson... probably because my level of understanding was just sufficient in order for me to complete the problems right in front of me, but not enough to truly understand and apply what I had just learned to more complex situations. Oh well. Hopefully after updating this blog with the lessons I covered last night, I'll be somewhat more refreshed (and a gain deeper understanding)!

// literal notation creates a single object
var jenny = {
    job: "student",
    married: false
};

// constructor notation involves defining an object constructor using the function keyword
function Person(job, married) {
    this.job = job;
    this. married = married;
}
// create a "jenny" object using the Person constructor
var jenny = new Person("student", false);

Methods are essentially functions associated with objects, remember?
function someObj() {
this.someMethod = function() {
};
}

// add a speak method to the Person constructor via constructor notation 
function Person(job, married) {
    this.job = job;
    this.married = married;
    this.speak = "Hello!"
}

// add method to object via literal notation
var jenny = {
    job: "student",
    married: false,
    speak: function(mood) {
        console.log("Hello, I am feeling " + mood); 
};

jenny.speak("fantastic");
jenny.speak("meh");


When defining a method for an object, use this.propertyName to reference other properties in that object. When that method is called, this.propertyName will always refer to the most recent value of propertyName.

var jenny = {
    job: "student",
    married: false,
    sayJob: function() {
        console.log("Hi, I work as a " + this.job); 
    }
};

// jenny's first job
jenny.sayJob();

// change jenny's job to "coding wizard with big fluttery beard"
jenny.job = "coding wizard with big fluttery beard";

//jenny's second job:
jenny.sayJob();

Throughout this post, I've been using dot notation to get the value of an object's property:
someObj.propName
However, we can also use bracket notation:
someObj["propName"] 

The advantage of using bracket notation is that we aren't restricted to using only strings in the brackets. We can also use variables whose values are property names:
var someObj = {propName: someValue};
var myProperty = "propName";
someObj[myProperty]

// some Obj[myProperty] = someObj["propName"] 
/* first set aProperty to a string of the first property in jenny (ie. the job property), then print jenny's job using bracket notation and a property */
var aProperty = "job";

console.log(jenny[aProperty]; 
);

Thursday, April 18, 2013

Javascript: Objects in Review


Objects give us a way to represent things--IRL or virtual. We're able to do this by storing information within the object's properties.

So far, we have learned two ways to make objects:
// literal notation, where we use var Name = { }; 
var cutedork = {
    age: 18,
    country: "United States"
};

// constructor notation, where we use the keyword new
var cutedork2 = new Object(); 
    cutedork2.age = 18;
    cutedork2.country = "United States";

Remember what properties are? They're similar to variables... except that they belong to an object and hold information. We can access properties in two ways:

// dot notation, with ObjectName.PropertyName
var age = jenny.ages

// bracket notation, with ObjectName["PropertyName"] (--don't forget the quotes!)
var country = jenny['country']

Methods act like functions associated with an object and they're especially useful when you ether want to:
1. Update the object properties
2. Calculate something based on an object's properties

// example of defining area and perimeter methods
function Circle (radius) {
    this.radius = radius;
    this.area = function () {
        return Math.PI * this.radius * this.radius;
    };

function Perimeter (radius) {
    this.radius = radius;
    this.area = function() {
        return 2 * Math.PI * this.radius;
    };
}}

Lastly--in addition to our basic object constructor, we can create our own custom constructors which are helpful for two reasons:
1. We can assign our object properties through parameters we pass in when the object is created.
2. We can give our object methods automatically.

// 3 lines are required to make mdfrmscrtch
var mdfrmscrtch = new Object(); 
mdfrmscrtch.blogURL = "http://mdrmscrtch.blogspot.com";
mdfrmscrtch.creator = "Jenny"

// A custom constructor for blog
function Blog (blogURL, creator) {
    this.blogURL = blogURL;
    this.creator = creator;
}

// Use this new creator to make hello_cutedork in one line!
var hello_cutedork = new Blog("http://hellocutedork.blogspot.com", "Jenny");

Song of the day // Lucky Ones (Lana Del Rey)