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

Thursday, January 1, 2015

Day 63: Codecademy Javascript Course

I've been preoccupied with the holidays, as my family flew to New York for Christmas/New Years.  I've been squeezing some coding in here and there, working on a Codecademy Javascript course, to complement the "Introduction to Programming" course on Treehouse, which is also on Javascript.

In Javascript, when we want a line of text to be ignored, we start the line off with two forward slashes, like so: 

//

Data comes in various types, including numbers and strings.  Numbers are self-explanatory, while strings are sequences of characters.  Another date type is the boolean, which is a data type having two values (usually denoted true and false).  Equal to is represented by ===, while !== means not equal to.  Greater than is >, less than is <, while greater than or equal to is >= and less than or equal to is <=.

If we enter:

confirm("Would you like to enter?")

A popup will appear on the page with the text and the options to hit cancel or ok.  If the user hits cancel, a "false" will be output into the console, if the user hits ok, a "true" will be output into the console.  Multiple sequential confirm lines will create multiple sequential popups.  We can use a semicolon at the end of each grouped line of code to separate the next group of code from the one prior.

I went over Modulo, which returns the remainder of two numbers that are divided, like so:

5 % 2

Would return a 1, as 2 goes into 5 2 times, with a remainder of 1.  If we do:

30 % 10

Then we would get a result of 0, because the remainder is 0.  I input this into the course:

if( 10 % 2 === 0) {
    console.log("The first number is even");
} else {
    console.log("The first number is odd");
}

And the output was "The first number is even," which means that the input evaluated to "true."  

I entered this:

if (15>4) {
    console.log("Adan is cool");
}

In order to print out "Adan is cool" in the log.

I entered this:

console.log("January".substring(0, 3));
console.log("Melbourne is great".substring(0, 12));
console.log("Hamburgers".substring(3, 10));

In order to print out:

Jan
Melbourne is
burgers

The .substring returns the desired letters.  "0" is the spot before the first letter, while "1" is the spot after the first letter, and so on, so for the letter you want to begin at, you enter the number before it (0 for the first letter, 1 for the second, and so forth), while for the letter you want to end at, you enter the number of the letter, because the number to the right of the letter corresponds to one below it's place in the sequence, while the number to the right of the letter is the same as the letter's place in the sequence of letters or spaces.

Here's a conditional statement:

if ( "Adan Camacho".length < 5) {
     console.log("Let's go down the first road!");
}
else {
     console.log("Your name is greater than 5 letters!");
}

We use variables to store data types.  For example:

var myCountry = "England"

Would store the string "England", which is a data type, inside the variable myCountry.  So then if I entered this:

console.log(myCountry.length)

The output would be 7, because England has seven characters.  Notice that myCountry is not in quotation marks, because it's a variable, as opposed to a string.

Then I entered this code for the final question:

if ("John".length > 5) {
     console.log("Apple");
}
else {
     console.log("I finished my first course");
}

The output was "I finished my course", which was the last part of the first Javascript course on codecademy.  I then went through this course once more, just to refresh the concepts, since I had been working on the course in small increments, sporadically, during the holidays, and I found this review to be tremendously useful.

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: 306

Thursday, December 18, 2014

Day 62: Introduction to Programming (Javascript)

The next section of the Odin Project is an introduction to javascript.  However, on the Treehouse Front End Web Development track, the next course is "Introduction to Programming."  Now, still in Treehouse, right after that course, comes "Javascript Foundations."  So, because of that, I think now would be a good time to get "Introduction to Programming" knocked out, that way I can get that out of the way and get started on Javascript on Treehouse at the same time that I do so on The Odin Project.  

I started the "Introduction to Programming" course, and the programming language for the course is javascript, so it looks like I'm diving right into javascript.  Javascript is the language of the web browser.  TO access the Javascript console on the Chrome web browser, we can go to View, Developer, Javascript Console, or by pressing Command, Option, J.  REPL stands for Read, Evaluate, Print, Loop.  To multiply in the Javascript Console, we use the * key, so 9*2 would result in an output of 18.  For text in javascript, we should wrap the text up in quotes (either double or single) to create a string.  When we insert a plus sign between two strings, javascript will join, or concatenate the strings together, so "Hello" + "World" would result in an output of "HelloWorld" in the console.

We used the alert(12) function to make a small popup appear on the screen with the number 12 in it.  The command alert(12) does not return or evaluate to anything, so it shows "undefined" in the console.  Alert is the function, and we are executing the function by entering parentheses with a value inside.  We used the prompt function, followed by parentheses with a string inside, to make the browser pop up a small window with a text box inside for the user to input information into.  We can also combine the prompt and alert functions to create sequentially appearing pop up boxes.

In order to add javascript to a website, we should first create the usual index.html site, and once that's created, in a folder near to it, we should create a file with a .js extension.  The name of the file does not matter, as long as the extension is .js.

The great thing is I actually feel pretty comfortable with HTML and CSS now.  I'm looking forward to the day I can say the same about javascript, jquery, ruby, and ruby on rails.  It's just a matter of putting in the time and soon I'll be able to say I'm a web developer!

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: 302