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

No comments:

Post a Comment