Thursday, February 26, 2015

Day 76: Head First Javascript

Today I continued with the Head First Javascript book, starting on pg 29, where I left off yesterday.  I started off the day working on a "99 Bottle of Beer on the Wall" game. 

This is the original version:

var word = "bottles"; 
var count = 99; 
while (count > 0) {
console.log(count + " " + word + " of beer on the wall,"); 
console.log(count + " " + word + " of beer,"); 
console.log("Take one down, pass it around,");
count = count - 1;
if (count > 0) {
console.log(count + " " + word + " of beer on the wall.");

else {
console.log("No more " + word + " of beer on the wall.");

}

This is my version, correcting the grammar for when there is only one bottle of beer left on the wall:

var word = "bottles"; 
var word1 = "bottle";
var count = 99; 
while (count > 0 && count > 1) {
console.log(count + " " + word + " of beer on the wall,"); 
console.log(count + " " + word + " of beer,"); 
console.log("Take one down, pass it around,");
count = count - 1;
if (count > 1) {
console.log(count + " " + word + " of beer on the wall.");
}
else if (count === 1) {
console.log(count + " " + word1 + " of beer on the wall.");
console.log(count + " " + word1 + " of beer on the wall,"); 
console.log(count + " " + word1 + " of beer,"); 
console.log("Take one down, pass it around,");
console.log("No more " + word + " of beer on the wall.");
}
else {
console.log("No more " + word + " of beer on the wall.");



That was a fun little exercise and a great way to start my day!  My next assignment is to build a Battleship-like game using javascript.  I set up the index.html file, inserted the link to the external javascript file, and created the external javascript file (battleship.js).  The link is like so:

<script src="battleship.js"><script>

I inserted that script right above the closing body tag, where the current standard practice recommends links to external javascript code be inserted.  One of the reasons this was recommended as an ideal insertion point is that it allows the webpage to load for the user before any javascript code is processed, so the user can have something to look at in case the code takes some time to process.  Sounds reasonable.  

When creating a variable, we don't have to necessarily give it a value, and if we don't, then javascript will default the variable to a value of undefined.  

SUMMARY OF CODING SKILLS

Total Treehouse Points: 5,151

Treehouse Points by Subject Matter (Miscellaneous not included): 
HTML:                                663 
CSS:                                1,599 
Design:                            1,193 
Development Tools:            747 
Javascript:                         916

Treehouse Ranking (%): "You have more total points than 91% 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, switched focus from web design to web dev)
Git Basics
Introduction to Programming
Javascript 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
In Progress: "Eloquent JavaScript," by Marijn Haverbeke (On pg 27)
In Progress: "Head First Javascript," by Eric Freeman and Elisabeth Robson (On pg 51)

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.5
Total Hours Coding: 365.5

Saturday, February 21, 2015

Day 75: Head First Javascript

All right, so now that I'm refocused, today's work began with the Head First Javascript book.  I already had an idea of what compiling meant, but the book defined it.  Compiling is the process through which your code goes through which produces a machine efficient representation of it, usually optimized for runtime performance.  With conventional languages like C, C++, or Java, you compile the code before you execute it.  Scripting languages, like javascript, are typically interpreted, which means the browser runs each line of code as it gets to it.  Scripting languages place less importance on runtime performance, and are more geared towards tasks like prototyping, interactive coding, and flexibility.  In the early days of javascript, performance was not so great due to this, but in recent years however, browser manufacturers have made it so that javascript, an interpreted language, can be compiled on the fly.

So, with javascript, you now have the conveniences of a scripting language, while enjoying the performance of a compiled language.  The word ECMA Script will pop up every so often when learning about javascript.  ECMAScript is the standard language definition for all javascript implementations.  The current implementation is ECMAScript 5, and ECMAScript 6 is currently being worked on.

A keyword is a reserved word in javascript, like var, function, true, false, break, or delete, for example.  We cannot use these keywords as names for variables.  In javascript, case does matter, so if we use two sample variable names, thisVariable and thisvariable, they would be treated as two different variables.  Although we are allowed to begin variable names with _ and $, we should avoid doing so.  

We wrote a simple function:

var total3 = 3
var total5 = 5

function finalTotal() {
document.write(total3 * total5);
}

finalTotal();

We went over while loops, and this reminded me of my Project Euler problem, which I need to solve, so I started working on a solution.  My first Project Euler Problem is this: 

If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.  Find the sum of all the multiples of 3 or 5 below 1000.

This is what I have so far:

 Multiples of 3

i = 0
while (i < 999) {
var i = i + 3;
document.write(i);
}

Multiples of 5

i = 0
while (i < 999) {
var i = i + 5;
document.write(i);

}

So, I'm able to get the necessary numbers to appear on the screen, but I have to figure out how to add the result of each loop iteration to the result of the prior loop iteration, and then, add the results of both loops to each other.  It's a start!

I learned that DOM stands for Document Object Model, but we didn't go into what exactly this means.

SUMMARY OF CODING SKILLS

Total Treehouse Points: 5,151

Treehouse Points by Subject Matter (Miscellaneous not included): 
HTML:                                663 
CSS:                                1,599 
Design:                            1,193 
Development Tools:            747 
Javascript:                         916

Treehouse Ranking (%): "You have more total points than 91% 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, switched focus from web design to web dev)
Git Basics
Introduction to Programming
Javascript 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
In Progress: "Eloquent JavaScript," by Marijn Haverbeke (On pg 27)
In Progress: "Head First Javascript," by Eric Freeman and Elisabeth Robson (On pg 29)

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.5
Total Hours Coding: 361

Sunday, February 15, 2015

Day 74: Organizing Myself to Make Progress on Javascript

I enjoy the problem-solving aspect of coding in javascript.  While that aspect is there in CSS to an extent when we finesse code to make pages look a certain way, it's much more pronounced in Javascript (in my, admittedly small, experience so far), and this makes me enjoy my javascript classes quite a bit.

When naming variables, we cannot start the name with a number.  Starting with a caps lock, underscore, or dollar sign is fine.  We can't use certain javascript words, like if, else, function, continue, switch, and more.  I went over scope again, in regards to variables declared within and outside of a function, and variables declared as global or local variables.

I learned today that remainder is another word for modulo, and that remainder is actually the more accurate term.  So:

100 % 10 = 0

That means 100 divided by 10 gives a remainder of 0. 

The current goal is to keep studying javascript, using multiple sources (Codecademy, Treehouse, and several books), until I become fluent.  This approach takes time, and will not be as brief as sticking to only one source, but it means I get to cover the same subject from multiple angles by multiple instructors/authors, gleaming deeper insight into the subject matter than I would otherwise.  I am ok with the additional time this will take, as I am looking for a solid grasp of the language.

There are three special values in javascript that are considered numbers but don't behave like numbers.  They are Infinity, -Infinity, and NaN.  The two infinities represent the positive and negative infinities.  Infinity - 1 is still infinity.  The infinities, according to Eloquent Javascript, are not mathematically solid, so we should not put too much trust in them.  NaN stands for Not a Number (but the value itself is a value of the number type).  0/0, for example, will yield NaN.  Infinity and -Infinity will also yield NaN if you try to calculate them.

I learned that strings can be in single or double quotes, but the entire string must be on only one line of code.  A backslash (\) will allow you to spread a string over several lines of code.  If you actually want to enter a backlash into the string, then enter two backslashes, like so: 

\\

I lost a bit of focus over the last week, which can happen when so many learning sources are available.  So I went back and organized myself, so as to re-focus.  The Odin Project serves as my overarching syllabus, and the current instructions are to solve three project Euler problems as well as to complete certain sections of the Codecademy Javascript course, except that if I wish, I can complete the entire Codecademy Javascript course, and doing so is considered extra credit at the moment.  I have finished the section on arrays, and the rest of the course deals with objects, but I'm not too familiar with objects, so I stopped there for now.  Going back to The Odin Project's Euler problems, I'm not fluent enough in Javascript at the moment to solve them.  So, I'm pausing to read "Head First Javascript," by Eric Freeman and Elisabeth Robson.  Since the Head First HTML and CSS book was excellent, I'd like to go through their Javascript book, take the Treehouse course on Loops, Arrays, and Objects, finish the Javascript Codecademy course, and then assess the Euler Project problems once more.  This is actually quite a lot of work, but I'm looking forward to it!

SUMMARY OF CODING SKILLS

Total Treehouse Points: 5,151

Treehouse Points by Subject Matter (Miscellaneous not included): 
HTML:                                663 
CSS:                                1,599 
Design:                            1,193 
Development Tools:            747 
Javascript:                         916

Treehouse Ranking (%): "You have more total points than 91% 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, switched focus from web design to web dev)
Git Basics
Introduction to Programming
Javascript 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
In Progress: "Eloquent JavaScript," by Marijn Haverbeke (On pg 27)
In Progress: "Head First Javascript," by Eric Freeman and Elisabeth Robson (On pg 1)

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.5
Total Hours Coding: 356.5

Saturday, February 14, 2015

Day 73: Javascript Conditional Statements

Either way, just remember it's left to right, not right to left, and PE MD AS is a useful tool.  Today, we added to the guessing game, like so:

var correctGuess = false;
var randomNumber = Math.floor(Math.random() * 6 ) + 1;
var guess = prompt('I am thinking of a number between 1 and 6. What is it?');
if (parseInt(guess) === randomNumber ) {
  correctGuess = true;

if ( correctGuess ) {
    document.write('<p>You guessed the number!</p>');

else if (parseInt(guess) < randomNumber) {
  document.write("<p>Try a higher number!</p>")
  var guessAgain = prompt("I am thinking of a number between 1 and 6. What is it?")  
}  
else if (parseInt(guess) > randomNumber) {
  document.write("<p>Try a lower number!</p>")
  var guessAgain = prompt("I am thinking of a number between 1 and 6. What is it?")  
}  

if (parseInt(guessAgain) === randomNumber) {
  correctGuess = true;
}

if (correctGuess) {
  document.write("<p>Congratulations, you are a good guesser, " + guessAgain + " is correct!</p>")
}
else {
    document.write('<p>Sorry. The number was ' + randomNumber + '. Try Again!</p>');

}

The new game gives the user a second chance to get it right.  It gives them a hint after the first attempt, which tells the user to make another attempt and select a higher or lower number.  Oh, I found a bug in the new game I made, it happens when the user selects the correct answer on the first attempt.  Working on it...as an aside, if when making text display, this works (note the quotation marks):

document.write("<p>Sorry. The number was" + randomNumber + ".</p>")

Here's my updated version of the game:

var correctGuess = false;
var randomNumber = Math.floor(Math.random() * 6 ) + 1;
var guess = prompt('I am thinking of a number between 1 and 6. What is it?');

if (parseInt(guess) === randomNumber ) {
  correctGuess = true;
} else if (parseInt(guess) < randomNumber) {
    var guessMore = prompt("Try a number higher than " + guess + "!"); 
    if (parseInt(guessMore) === randomNumber) {
    correctGuess = true;
   }
}
  else if (parseInt(guess) > randomNumber) {
    var guessLess = prompt("Try a number lower than " + guess + "!");
    if (parseInt(guessLess) === randomNumber) {
    correctGuess = true;
   }
}

if (correctGuess) {
    document.write('<p>You guessed the number!</p>');

else {
    document.write("<p>Sorry. The number was " + randomNumber + ".</p>")

}

This version is copied straight from the class, so it's definitely not "my version."  We then went over the && operator and the || operator.  We can string together any number of && or || operators.  When working with operators, all of the conditions within the operators must be full conditions, for example variable = b + 1 is good, but simply entering a string, like "cake," is not ok, as there is no condition to be rated true or false.  This is my code for a five-question Quiz:

var beginningScore = 0;

var answer1 = prompt("What country are Spaniards from?");

if (answer1.toUpperCase() === "SPAIN") {
  beginningScore += 1;
}

var answer2 = prompt("What country are Japanese from?");

if (answer2.toUpperCase() === "JAPAN") {
  beginningScore += 1;
}

var answer3 = prompt("What country are Germans from?");

if (answer3.toUpperCase() === "GERMANY") {
  beginningScore += 1;
}

var answer4 = prompt("What country are Brazilians from?");

if (answer4.toUpperCase() === "BRAZIL") {
  beginningScore += 1;
}

var answer5 = prompt("What country are Mexicans from?");

if (answer5.toUpperCase() === "MEXICO") {
  beginningScore += 1;
}

document.write("<p>Your final score is " + (beginningScore * 20) + ".</p>");

if (beginningScore === 0) {
  document.write("<p>You have won a participation award!</p>");
}
else if (beginningScore === 1 || beginningScore === 2 || beginningScore === 3) {
  document.write("<p>You have won a Bronze Medal!</p>");
}
else if (beginningScore === 4) {
  document.write("<p>You have won a Silver Medal!</p>");
}
else if (beginningScore === 5) {
  document.write("<p>You have won a Gold Medal!</p>");

}

It works!  The next and final badge is called Creating Reusable Code with Functions.  It's the final badge in the Javascript Basics course.  If I finish it today, then I think I will break 5,000 points on Treehouse, which would be a great milestone to cross for me.  I'm pretty motivated, I'm going to stay up tonight until I finish the final badge, completing the Javascript Basics course.  Functions are created like this:

function goToCoffeeShop() {
     alert("Coffee is on the way!");
}

The function naming rules are the same as the previous rules we went over (no spaces, can't start with a number, can only be made up of letters, numbers, the _ sign, and the $ character, and we can't use any other punctuation in the name).  To call the function above, enter the code like so:

goToCoffeeShop();

That's it.  Simple enough.  You can also create a function inside a variable, and if you do so, you would add a semicolon at the end of the last curly brace (unlike with a regular function).  Here's an example:

var goToCoffeeShop = function() {
     alert("Coffee is on the way!");
};

And here is how you would call that function: 

goToCoffeeShop();

Same as calling a function created the other way.  Here's a function we wrote:

function alertRandom() {
 var randomNumber = Math.floor( Math.random() * 6 ) + 1;
  alert(randomNumber);
}


alertRandom()

It calls a random number.  Functions change the flow of the program, as when the browser reads it, it jumps to the area where the code making up the function is at, and once finished with that code, it jumps to the area right below the code that called the function.  It's a good idea to put your functions together at the top of your script.  We don't have to have an alert inside a function.  Many times we will have a return statement in a function.  If we do, it is a good idea to have the return statement at the end of the function, because a return statement causes the javascript to exit the function immediately.  The return statement inside of a function can only return a single value (a string, boolean, number, or the contents of a variable), so you could not do this:

function myFunction() {
     return "Mon", "Tues", "Wed", "Thurs", "Fri";
}

That would be illegal.  You can have multiple return statements in a function, but only one would ever run (as part of an if/else code, for example).  Hitting the cmd + option + j keys will call the javascript console for chrome on a mac.  This code allows you to make a dice of any number (in this case 20):

function getRandomNumber( upper ) {
  var randomNumber = Math.floor( Math.random() * upper ) + 1; 
  return randomNumber;
}


console.log(getRandomNumber(20));

When you call it, the number you put in the parentheses reflects how many sides the die has.  An argument is a value that you store in a parameter that is called whenever you call the function.  So, you can pass a piece of information, called an argument, to a function, the function stores that value in a parameter and uses it within the function.  Said another way, when you call a function, you pass an argument which is stored in a parameter in the function.  A function can also return a value that can be used in a different part of a program.  However, unlike a return value, which must be a single item, functions can accept multiple arguments.  When calling a function you can pass multiple arguments to the function.  Each argument is then stored in a separate parameter and is used as a separate variable within the function.  Here's an example:

function goToCoffeeShop(drink, pastry) {
     alert( drink + "and" + pastry + " are on the way!");
}

goToCoffeeShop("Coffee", "Bagel");

This is a very simple function that accepts a single argument, then returns that argument:

function returnValue(name) {
     return name;
}

This function returns the larger of two numbers:

function max(number1, number2) {
  if (number1 > number2){
  return number1;
  }
  else {
  return number2;
  }

}

Neat.  Variables created within a function stay within the function.  This code exemplifies this:

function greeting() {
     var person = "Lilah";
     alert(person);
}

var person = "George";
greeting();
alert(person);
greeting();

It produces output of Lilah, George, and then Lilah again.  Remember that the function code runs only AFTER it is called, NOT when the function is created/set.  This function is interesting in showing global and local scope.  Now, IF we remove the var keyword inside the function, then the function does change person to Lilah globally.  This is not good practice.  We should use the var keyword, to avoid setting global scope for a variable.  For example:

var message = "Welcome!";
function setMessage() {
     message = "Go away!";
}

setMessage();
alert(message); 

In the code above, the alert would output Go away! because we did not use the var keyword when defining message inside the function, which means the definition becomes global in scope, reaching outside the function.  This is not desirable.  I finished the Javascript Basics course today!  

These last 8 days have been fantastic!  I've met my goal of coding an average of 4.5 hours a day for 8 days now!  I feel really great, and I feel like I've learned quite a bit.  I plan on hitting Javascript material over and over until I'm fluent in Javascript.  :)

This is great!

SUMMARY OF CODING SKILLS

Total Treehouse Points: 5,103

Treehouse Points by Subject Matter (Miscellaneous not included): 
HTML:                                663 
CSS:                                1,599 
Design:                            1,193 
Development Tools:            747 
Javascript:                         868

Treehouse Ranking (%): "You have more total points than 91% of all students."

Treehouse Badge(s) Earned Today:

Making Decisions With Conditional Statements(Javascript Basics)
Javascript Functions(Javascript Basics)

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, switched focus from web design to web dev)
Git Basics
Introduction to Programming
Javascript 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)).
In Progress: "Eloquent JavaScript," by Marijn Haverbeke.

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.5
Total Hours Coding: 352