Monday, February 9, 2015

Day 68: Programming Basics Course on Treehouse (Javascript) and Javascript Classes on Codecademy

Today I continued with the Introduction to Programming Course on Treehouse, starting with a class on if/else statements.  In an if statement, the value that goes in the parentheses will be true or false, if it's true, the code inside the curly braces following the parentheses will run, while if it's false, the code will not run.

False values in Javascript: 0 (note: while 0 is a false value in javascript, other languages may define 0 as being a true value, so don't always assume 0 is a false value), the value false, an empty string, the value we call null (example, x=null), the value undefined (an example of an undefined value is var x; in which the variable x was created, but no value was assigned to it), 

True values found in Javascript: Numbers other than 0, the value true, a string with content (an empty space counts as content), the value counter, 

With an if statement, if the values in the parentheses evaluate to true, then the code inside the curly braces will run.  Example, in this case, the console will log "I am happy."  

if(5+5===10) {
console.log("I am happy")

}

But in this case:

if(5+5===4) {
console.log("I am happy")
}

It will not log anything.  If an if statement is false, nothing will happen, but if we want something to happen when an if statement evaluates to false, in that case, we can add an else statement below, like so: 

if(null) {
console.log("I am happy")
}
else {
console.log("I am sad")
}


Which will log "I am sad" to the console.  Here's an if/else statement combined with a variable: 

var name = prompt("What is your name?")

if(name) {
console.log("Welcome, " + name)
}
else {
console.log("Please try again, no input was received.")
}


This creates a prompt which asks the user's name, and then replies with a welcome for the user which includes the user's name.  In the event that the user did not enter anything into the prompt and simply selected ok, the log will output "Please try again, no input was received."

Next, we went into loops, which will execute code over and over again.  the first kind of loop we went over was the while loop.  Let's say we wanted to log "Hello World" ten times.  One way to do that is to simply do a console.log("Hello World"); ten times, but there's a better way, with loops.  A loop like this:

console.log("Before")
while (counter){
console.log("Hello World");
}

console.log("After")

Will repeat infinitely, causing our browser to crash.  Counter is a true value, so the console will log "Hello World" infinitely.  In order to prevent this from happening, we should do this:

var counter = 10;

console.log("Before")
while (counter){
console.log("Hello World");
counter = counter - 1;
}

console.log("After") 

What that does is assign a value of 10 to counter.  The first time the loop runs, it will log "Hello World," and then continue with the code right below, which will evaluate to 9, which will then be entered in the counter value in the parentheses after while.  When the code is run the second time, it will log "Hello World," then it will get to the counter = counter - 1 line and evaluate to 8, and then run again, because 8, like 9 and 10, evaluates to true.  It will keep doing this forever until it can evaluate to false.  Luckily for us, that will not take long, as on the 11th attempt, when the counter = counter - 1 evaluates to 0, the code will run one more time, and evaluate to false.  This creates an infinite prompt asking for the user's name:  

var name = prompt("What is your name?")

while (prompt("What is your name?")) {
console.log("Welcome " + name);

}

You can stop it by selecting cancel on the prompt, but this is not very useful.  After the while loops, we went over for loops.  With a for loop, we can enter three values (separated by two semicolons) into the parentheses after for.  The for loop is more common than the while loop, because of this built-in feature.  Both loops serve the same purpose, however, the for loop is more structured, while the while loop is more free form.  This is an example: 

for (var counter=10; counter; counter = counter -1) {
console.log("Hello World", counter);

}

Which will log this:

Hello World 10
Hello World 9
Hello World 8
Hello World 7
Hello World 6
Hello World 5
Hello World 4
Hello World 3
Hello World 2

Hello World 1

The number after Hello World shows the counter as it is decreasing every time the code runs.  The first section inside the parentheses is called the initialization, it only runs once, when you first hit the for loop.  The second section inside the parentheses sets the condition, if the condition is true, the code will run, while if it is false, it will not run.  The third section inside the parentheses sets the increments (or decrements) in which the code will run through the condition, if it runs at all.  The third section of the for loop actually runs right after the for loop, even though it is set in the third section of the parentheses, that spot is not where it runs.  Note that if the second section is false, the code will not run, and neither will the third section, which would otherwise have run right after the loop.

For loops are great when you find you need to loop, and you know how many times the loop needs to be repeated.  While loops, on the other hand, are great for when you have to loop, but you don't know how many times you have to loop ahead of time.  Here's a why loop, followed by a for loop:

var counter = 2

while(counter) {
    console.log("This is the why loop!");
    counter = counter - 1;
}

var counter = 1

for (counter; counter < 5; counter++) {
    console.log("This is the for loop!");

}

Notice that I changed the value for var counter midway through the code.  Javascript lets us do that.  Next, we went over the do/while loop, and this is my example loop:

var loopCondition = false
var getToDaChoppa = function(){
    do {
console.log("Fast!");
} while (loopCondition);
};


getToDaChoppa(); 

It outputs "Fast!" once, then does not runt the while loop because the condition is false.  Next, here is a for loop, followed by a while loop, followed by a do/while loop. 

var counter = 10

for (counter; counter < 21; counter++){
    console.log("I am counting from 10 to 20, the current number is " + counter);
}

counter = 3

while (counter) {
    console.log("This is a while loop stopping after three loops");
    counter = counter -1;
}

counter = false

do {
    console.log("This is the do loop.");} 

    while(counter);

I finished some more of the Codecademy Javascript classes today.  With this code: 


var youHit = Math.floor(Math.random() * 2)

Javascript selects either 0 or 1, and 0 means false, while 1 means true.  I completed a Codecademy class which had me create this code: 

var slaying = true

var youHit = Math.floor(Math.random() * 2)

var damageThisRound = Math.floor(Math.random() *5 + 1)

var totalDamage = 0

while(slaying) {
    if (1) {
        console.log("Congratulations, you hit the dragon."         );
        totalDamage += damageThisRound;
        if (totalDamage >= 4 ) {
            console.log("The player slew the dragon.");
            slaying = false
        }
        else {
            youHit = Math.floor(Math.random() * 2); 
        }
    }
    else {
        console.log("The dragon defeated you.");
    }
    slaying = false

}

For slaying a dragon!  We then went over switches, and I finished that section with this code: 

var favoritePlanet = prompt("What is your favorite planet?");

switch(favoritePlanet) {
    case 'Mars':
    console.log("That's a planet similar to Earth!")
    break;
    case 'Neptune':
    console.log("Neptune was the Roman god of the sea!")
    break;
    case 'Saturn':
    console.log("Saturn has rings!")
    break;
    default:
    console.log("Please repeat your selection, as we do not have that planet in our database.");
    break;

}

After that, we went over logical operators, of which Javascript has three, and (&&), or (||), and not (!).  The class walked me through creating this simple "choose your own adventure" game:

var user = prompt("You're an astronaut exploring mars, and need to seek shelter, as a radiation storm is approaching, do you seek shelter in a cave, in your tent, or panic (CAVE, TENT, or PANIC)?").toUpperCase();

switch(user) {
    case 'CAVE':
    var fast = prompt("Do you walk fast?");
    var medkit = prompt("Did you bring the medkit?");
    if (fast === "yes" && medkit === "yes") {
        console.log("You survive");
    }
    else {
        console.log("The radiation kills you."); 
    }
    break;
    
    case 'TENT':
    var tentPoles = prompt("Did you bring the tent poles?");
    var instructions = prompt("Did you bring the instructions?");
    if (tentPoles === "yes" || instructions === "yes") {
        console.log("You've survived!");
    }
    else {
    console.log("It looks like you suffer from radiation poisoning");
    }
    break;
    
    case 'PANIC':
    console.log("May the Force be with you!");
    break;
    default:
    console.log("We don't recognize that option.");

    }

Tomorrow, we're going over arrays and operators!  

SUMMARY OF CODING SKILLS

Total Treehouse Points: 4,313

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

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

Treehouse Badge(s) Earned Today:
Control Structures (Introduction to Programming)

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: 9
Total Hours Coding: 329.5

No comments:

Post a Comment