Sunday, January 25, 2015

Day 66: Javascript "For" Loops

Today's class deals with "for" loops.  The general syntax for this kind of loop is:

for (var i = 1; i < 11; i = i + 1){
console.log(i);
}

The console.log is not a part of the syntax for the loop, we are just using it in order to see the output printed on the log.

for (var i = 4; i < 24; i = i + 1) {
console.log(i);
}

The code above returns every number between 4 and 23, including 4 and 23.  The i = i + 1 code can also be written as i++, which will start at the beginning and increment, while i-- will start at the end and decrement.  Continuing with this, i += x will increment by the value of x, while i -= x will decrement by the value of x.  A JavaScript loop that cannot properly end is called an infinite loop, and it will crash a browser.  "For" loops will only run when the condition is true.

These were the instructions:

Once more, for practice: write a forloop that gets the computer to count down from 100 until 0 by 5. This time, make sure not to print 0.

And this was my code, which was correct (the i >= 3 can have an x value of 2, 3, 4, or 5).

for (var i=100; i >= 3; i-= 5){
    console.log(i);

}

Next, we started going over arrays.  This was my first array:

var junk = ["Data One", "Data Two", 8, 88];
console.log(junk)

The console.log is not a part of the array, it's just what is used to print the output to the log.  This will output the 4th element in an array (array numbering starts at 0, so 3 will output the 4th item):

console.log(junkData[3])

This code will print out every element of an array:

var cities = ["Melbourne", "Amman", "Helsinki", "NYC", "Toronto", "Mecca", "Buenos Aires"];

for (var i = 0; i < cities.length; i++) {
    console.log("I would like to visit " + cities[i]);
}

This:

var names = ["George", "Edward", "Ralph", "Denise", "Veronica"];
for (var i = 0; i < names.length; i++) {
    console.log("I know someone called" + " " + names[i]);
}

Will output "I know someone called George" as well as the same output with the other names.  That finished the first section of the "For" loops class.

SUMMARY OF CODING SKILLS

Total Treehouse Points: 4,236

Treehouse Points by Subject Matter: HTML 663, CSS 1,599, Design 1,193, Development Tools 747, and Miscellaneous
Treehouse Ranking (%): "You have more total points than 88% of all students."

Treehouse Badge(s) Earned Today:

Treehouse Courses Completed:

How to Make a Website
HTML
CSS Foundations
CSS Layout Techniques
Aesthetic Foundations
Design Foundations
Adobe Photoshop Foundations
Adobe Illustrator Foundations (66% complete, but switched focus to web dev, as opposed to web design)
Git Basics

Codecademy (& other) Courses Completed:
HTML and CSS (Codecademy) 

Books Read or in Progress:

Completed: "Head First HTML and CSS," by E. Robson & E. Freeman (37 pg preface and 710 pgs of actual content (as in, I'm not including the book's index))

My Progress on The Odin Project:
1.  Introduction to Web Development             100% Complete
2.  Web Development 101                                29% Complete
3.  Ruby Programming                                       0% Complete
4.  Ruby on Rails                                               0% Complete
5.  HTML5 and CSS3                                           0% Complete
6.  Javascript and JQuery                                  0% Complete
7.  Getting Hired as a Web Developer                 0% Complete

Hours Spent Coding Today: 2
Total Hours Coding: 316

Friday, January 23, 2015

Day 65: Javascript Functions (Codecademy)

I started the day off with the Introduction to Functions course in Codecademy.  I started the day by using the return keyword:

// Parameter is a number, and we do math with that parameter
var timesTwo = function(number) {
    return number * 2;
};

// Call timesTwo here!
var newNumber = timesTwo(5)
console.log(newNumber);

The output was 10.  Note how the value returned from timesTwo() is automatically assigned into newNumber.  This was my next function, using the return keyword (remember the % sign means modulo).

// Define quarter here.
var quarter = function(number) {
    return number / 4;
}

if (quarter(24) % 3 === 0 ) {
  console.log("The statement is true");
} else {
  console.log("The statement is false");

}

The output is:

The statement is true

I then created a function for finding the perimeter of a box:

// Write your function starting on line 3

var perimeterBox = function(length, width) {
    return ((length * 2) + (width * 2));
};

console.log(perimeterBox(4, 2));

The output in this case was 12.

Variables defined inside of a function are local variables, while variables defined outside of a function are global variables.  The var keyword creates a new variable in the current scope.  That means if var is used outside a function, that variable has a global scope.  If var is used inside a function, that variable has a local scope.  This input shows this concept:

var my_number = 7; //this has global scope

var timesTwo = function(number) {
    var my_number = number * 2;
    console.log("Inside the function my_number is: ");
    console.log(my_number);
}; 

timesTwo(7);

console.log("Outside the function my_number is: ")

console.log(my_number);

The output is:

Inside the function my_number is:
14
Outside the function my_number is:
7

I entered this function:

var nameString = function (name) {
    return("Hi, I am" + " " + name);
};

console.log(nameString("Adan"));

And the output was:

Hi, I am Adan

This was the next function:

var sleepCheck = function(numHours) {
    if (numHours >= 8) {
        return("You're getting plenty of sleep! Maybe even too much!");
    }
    else {
        return("Get some more shut eye!");
        
    }
};

sleepCheck(2);

And the output was:

"Get some more shuteye!"  

With that function, I finished the Introduction to Functions course on Codecademy.  The next course is called "Build "Rock, Paper, Scissors,"" and it's a course on how to build that game using JavaScript.  This is the game:

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

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

This first step is to create this variable:

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

This creates a prompt into which the user enters his choice (rock, paper, or scissors).  We then entered this:

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

computerChoice = Math.random();


console.log(computerChoice);

Which printed out a random number between 0 and 1 (in this case, 0.37306072982028127).  The code below follows:

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

computerChoice = Math.random();

console.log(computerChoice);

if (computerChoice <= 0.33) {
    computerChoice="rock";
}
else if (computerChoice >= .34 && computerChoice <= .66) {
    computerChoice="paper";
}
else {
    computerChoice="scissors";

}

The output was:

"scissors"

The next phase is below:

/*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";
} console.log("Computer: " + computerChoice);*/

This was next:

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

};

In the code above, I had entered ==== instead of === in one instance, and this error held me up quite a bit, as I didn't spot it at first.  Below is the complete game:

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";
} console.log("Computer: " + computerChoice);

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

compare(userChoice, computerChoice)

It works!  I entered the code into the JavaScript Console on Google Chrome, and the game works!  How cool!  I then added this code to handle inappropriate entries:

else if(choice1 !== "scissors" || "rock" || "paper") {

        prompt("Please enter a valid selection (note: the system does not recognize capital           letters)")

It worked, except that it only works once.  So, if the user keeps entering incorrect selections, the prompt won't repeat itself.  I haven't learned how to do that yet, but based on perusing StackExchange right now, I think the JavaScript feature that allows that code to repeat itself if called a loop, which happens to be my next JavaScript course!

SUMMARY OF CODING SKILLS

Total Treehouse Points: 4,236

Treehouse Points by Subject Matter: HTML 663, CSS 1,599, Design 1,193, Development Tools 747, and Miscellaneous
Treehouse Ranking (%): "You have more total points than 88% of all students."

Treehouse Badge(s) Earned Today:



Treehouse Courses Completed:

How to Make a Website
HTML
CSS Foundations
CSS Layout Techniques
Aesthetic Foundations
Design Foundations
Adobe Photoshop Foundations
Adobe Illustrator Foundations (66% complete, but switched focus to web dev, as opposed to web design)
Git Basics

Codecademy (& other) Courses Completed:
HTML and CSS (Codecademy) 

Books Read or in Progress:

Completed: "Head First HTML and CSS," by E. Robson & E. Freeman (37 pg preface and 710 pgs of actual content (as in, I'm not including the book's index))

My Progress on The Odin Project:
1.  Introduction to Web Development             100% Complete
2.  Web Development 101                                29% Complete
3.  Ruby Programming                                       0% Complete
4.  Ruby on Rails                                               0% Complete
5.  HTML5 and CSS3                                           0% Complete
6.  Javascript and JQuery                                  0% Complete
7.  Getting Hired as a Web Developer                 0% Complete

Hours Spent Coding Today: 4
Total Hours Coding: 314

Wednesday, January 21, 2015

Day 64: Codecademy Javascript Course

I started off the day with this code:

var age = prompt("What's your age?");

if (age < 13){
     console.log("You're allowed to play, but I take no responsibility.");
}

else {
    console.log("Play on!");
}

I programmed this in Javascript and the tutorial congratulated me on writing my first game:

// Check if the user is ready to play!
confirm("I am ready to play!")

var age = prompt("What's your age?");

if (age < 13){
     console.log("You're allowed to play, but I take no responsibility.");
}

else {
    console.log("Play on!");
}

console.log("You are at a Justin Bieber concert, and you hear this lyric 'Lace my shoes off, start racing.'");

console.log("Suddenly, Bieber stops and says, 'Who wants to race me?'")

var userAnswer = prompt("Do you want to race Bieber on stage?")

if (userAnswer === "yes") {
    console.log("You and Bieber start racing. It's neck and neck! You win by a shoelace!");
}

else {
    console.log("Oh no!  Bieber shakes his head and sings 'I set a pace, so I can race without pacing.'");

var feedback = prompt("Rate my game out of 10")

if (feedback > 8) {
    console.log("Thank you! We should race at the next concert!");
}

else {
    console.log("I'll keep practicing coding and racing.");
}

I started working on functions in Javascript today.  This function yields an output of 2:

// This is what a function looks like:

var divideByThree = function (number) {
    var val = number / 3;
    console.log(val);
};

// On line 12, we call the function by name
// Here, it is called 'dividebythree'
// We tell the computer what the number input is (i.e. 6)
// The computer then runs the code inside the function!
divideByThree(6);

When naming functions, the convention is to use CamelCase, an example of which would be "sayHello," in that the first word is not capitalized, but the second word is, and there is no space between the two words (as a bit of trivia, in contrast we have Pascal case, which always begins with a capital letter, like "SayHello").

This is one of the lessons I worked on:

// Below is the greeting function!
// See line 7
// We can join strings together using the plus sign (+)
// See the hint for more details about how this works.

var greeting = function (name) {
    console.log("Great to see you," + " " + name);
};

// On line 11, call the greeting function!

greeting("John")

And the output was:

"Great to see you, John"

These are instructions from Codecademy, which I thought useful to save:

"The var keyword declares a variable named functionName.
The keyword function tells the computer that functionName is a function and not something else.
Parameters go in the parentheses. The computer will look out for it in the code block.
The code block is the reusable code that is between the curly brackets }. Each line of code inside } must end with a semi-colon.
The entire function ends with a semi-colon.
To use the function, we call the function by just typing the function's name, and putting a parameter value inside parentheses after it. The computer will run the reusable code with the specific parameter value substituted into the code."



The instructions go over how functions work.  I entered this function: 
var foodDemand = function(food) {
    console.log("I want to eat" + " " + food);
}; 
Then called it with this:
foodDemand("oranges")
And received this output: 
I want to eat oranges 
We should put a ; at the end of each line of code which is inside of { } and also right after the closing }.  The ; lets the computer know where there are stopping points in the code.  I learned of a programming principle called the D.R.Y. principle, which stands for "Don't Repeat Yourself."  
My next function returned the cost of oranges:
var orangeCost = function (cost) {
    console.log(cost*5);
};
orangeCost(5)
The output is 25.  Then I made my own function, just for practice: 
var howPretty = function (name) {
  console.log(name + " " + "is very pretty");  
};
howPretty("Rachel Phoenix") 
So then, I made this for my girlfriend:


I'm having fun with JavaScript.  :)

SUMMARY OF CODING SKILLS

Total Treehouse Points: 4,236

Treehouse Points by Subject Matter: HTML 663, CSS 1,599, Design 1,193, Development Tools 747, and Miscellaneous
Treehouse Ranking (%): "You have more total points than 88% of all students."

Treehouse Badge(s) Earned Today:



Treehouse Courses Completed:

How to Make a Website
HTML
CSS Foundations
CSS Layout Techniques
Aesthetic Foundations
Design Foundations
Adobe Photoshop Foundations
Adobe Illustrator Foundations (66% complete, but switched focus to web dev, as opposed to web design)
Git Basics

Codecademy (& other) Courses Completed:
HTML and CSS (Codecademy) 

Books Read or in Progress:

Completed: "Head First HTML and CSS," by E. Robson & E. Freeman (37 pg preface and 710 pgs of actual content (as in, I'm not including the book's index))

My Progress on The Odin Project:
1.  Introduction to Web Development             100% Complete
2.  Web Development 101                                29% Complete
3.  Ruby Programming                                       0% Complete
4.  Ruby on Rails                                               0% Complete
5.  HTML5 and CSS3                                           0% Complete
6.  Javascript and JQuery                                  0% Complete
7.  Getting Hired as a Web Developer                 0% Complete

Hours Spent Coding Today: 4
Total Hours Coding: 310