Tuesday, April 7, 2015

Day 87 - 91: Back to the Javascript Book

This blog entry will chronicle my studying from the period starting on April 3, 2015 and ending on April 9, 2015.  This period comprises the 7 days I will use to study javascript, with the goal being to take The Odin Project's exam on April 10, 2015.  I'll use this entry as a sort of quick reference for javascript basics.  NOTE INSERTED LATER: I changed tactics on April 7 in order to take the test in Ruby.  I will be going over the modules instead, but I put in 20 hours of JavaScript coding in the last couple of days.

I started the day on Chapter 10 of the javascript book, which dealt with "if" statements.  I learned that the equal sign is reserved for assigning a value to a variable, while the === sign is used for testing a variable for a value.  So, we should not use the single = when testing a variable for a value, for example in an "if" statement.  Here's an example of this concept:


if (var1 === var2) {

  var3 = var4;
}

So, above, var1 is being tested to see if it matches var2, so we use the triple === sign.  Then, on the second line, the value of var3 is being transferred to var4, so in that case, we use the singular = sign.  


Another comparison operator is !==, which is the opposite of ===, so !== means is not equal to.  The instructor says the double equal sign can be used instead of the triple equal sign, and the != can be used instead of the !==, but I'm sticking to === and !== at the instructor's request.  

Next is Chapter 12, which goes over "if...else" and "else if" statements.  With "if" and "else...if" statements, we have some parentheses after the "if" or "else if" with a condition within, but with "else" statements, there are no parentheses (no condition), there are only brackets with commands within. 

When being instructed to assign a variable to another, for example "assign a to b," we write it like so:

b = a;

So, "assign the number 8 to the variable x" is written like so:

x = 8;

In Chapter 13, we worked on testing sets of conditions with the or operator, || and with the and operator, &&.  These can be chained and parentheses can be used to clarify ambiguities.

In Chapter 14, we went over nested "if" statements.  Nested "if" statements can be used instead of "if" statements with the and operator, &&, as a part of the condition.

In Chapter 15, we went over arrays.  In an array, because the first element has an index value of 0, that means that the last element in an array always has an index value one number less than the amount of elements in the array.  So, for example, if an array has 10 elements in it, the index value of the tenth element would be 9 (because the first element has an index value of 0).  When choosing the variable name for an array, it is common to give it a plural name, for example cities instead of city, since an array is used to list things.  

In Chapter 16, we went over adding and removing elements from arrays.  If you happen to make an array with some empty elements, anytime you try to reference them, the output will be undefined.  You can remove the last element of an array like so (you don't have to identify the last element):

list.pop()

Assuming the array was named list, then the last item in that array would be removed.  You can also add elements to the end of an array like so:


list.push("Sample String", "Sample String")

The code above will add those two strings to the list array, at the end, in the same order as they are entered in the parentheses.

In Chapter 17, we went over removing, inserting, and extracting elements in an array.  This:

list.shift()

Will remove the first element in the list array.  This:

list.unshift(sample, sample, sample)

Will insert the designated elements in the beginning of the list array.  We learned about the .splice() command.  Suppose you have an array with the elements:

["dog", "cat", "fly", "bug", "ox"]  

The following code adds "pig", "duck", and "emu" after "cat" while removing "fly" and "bug".

pets.splice(2, 2, "pig", "duck", "emu");

The first digit in the parentheses is the index of the position where you want to start adding or deleting.  The second digit is the number of existing elements to remove, and it starts right after the element(s) that you just inserted.  It can be a little confusing, but just imagine that the .splice() command is inserting itself into that index spot and shoving whatever is already in that spot to the right.  The second number is then the amount of items to remove AFTER the items inserted.

Then we went over the .slice() command has a similar name, but does something different.  It copies one or more consecutive elements in any position in an array and puts copies of them into a new array (so it doesn't remove the originals).  A good way to remember is to think that sPlice "Pushes" or "Pastes" elements out of or into an array, while .slice() cannot push or paste, it can only copy. 

Lets say you have an array like this, named list, ["dog", "cat", "fly", "bug", "ox"].  The code below:

var newList = list.slice(2, 4);

Will copy "fly" and "bug" into your new array, newList.  The 2 is the index number at which you start, and the 4 is the index number after the index number of the last item you want to copy.  So you could visualize it like list.slice(index # to begin copying, index # after last copy).  Or perhaps list.slice(index # to begin copying, index # not to copy).  That should help.  If you happen to slice array elements into the same array, because you are giving the array variable a new value, the old array will be gone in that case, not because the copying destroyed it, but because transferring the slice data into the array variable replaces the prior array/data.

Chapter 18 goes over "for" loops, but before doing that, since I just went over arrays, I wanted to give Euler Problem 2 another shot.  Here's my solution from a week or two ago:

var fibArray = [1,2];
var total = 2;

    for (var i = 0; i < 30; i += 1) {
     var fib = fibArray[fibArray.length - 1] + fibArray[fibArray.length - 2];
     fibArray.push(fib);   
     if (fib % 2 === 0) {
     total = total + fib;
    
    }

    document.write(fibArray)

    console.log(total);

And then here's my new solution:

var fib = [1, 2];
var totalElements = 2;

for (var i = 0; i < 100; i += 1) {
  if (fib[fib.length - 1] + fib[fib.length - 2] < 4000001) {
  fib.push(fib[fib.length - 1] + fib[fib.length - 2]) 
  totalElements = totalElements + 1;
  }
}

document.write(fib);
console.log(totalElements);

var evenTotal = 0;

for (var i = 0; i < totalElements; i += 1) {
  if (fib[0] % 2 === 0) {
    evenTotal = evenTotal + fib[0];
    fib.shift();
  }
  else {
    fib.shift();
  }
}

console.log(evenTotal);

The thing is, in neither do I use a function.  In both of them, I'm figuring out the answer as I go along by running the Fibonacci sequence and then using my output to keep going with the formula.  By the way, the 100 in that for loop is simply a number of iterations, but it takes less than that many iterations, I just had to put a number there, but the thing is, the question remains, "How do you know it takes less than 100 iterations?"  Well, I know because I ran it and then I saw on the screen by testing various numbers, but that's not good enough.  I need to be able to solve the problem with a function in order to be prepared to take the test.  So, that's the goal right now.  By the way, here's my new and improved solution to Euler Problem 1:

var total = 0;

for (var i = 0; i < 1000; i ++) {
  if (i % 3 === 0 || i % 5 === 0)
    var total = total + i;
}

document.write(total);
console.log(total);

That one's clean, unlike my solutions to Euler Problem 2, which are quite convoluted.  In going over my solutions to the problems, in both cases, I found unnecessary code (in my first solution to Euler Problem 2 posted above, I removed the extra code).  By unnecessary  code I mean code that, if removed, did not affect the answer at all, it was 100%, completely superfluous.  I feel good about seeing that, because I'm seeing that my understanding of javascript keeps increasing, so that what I didn't notice as extra code the first time I solved the problem, I now noticed it as such when reading my code.  Nonetheless, I've got to solve Euler Problem 2 via the use of a function.  I could skip ahead in the book to the chapters on functions and get done with it, but I'm going to go over the chapters sequentially, to make sure I cover all the basics.

Anyhow, onwards with the book and I'll come back to this.  Wait...I figured out a fix for the "100" problem...I replaced 100 with fib.length, and it worked:

var fib = [1, 2];
var totalElements = 2;

for (var i = 0; i < fib.length; i += 1) {
  if (fib[fib.length - 1] + fib[fib.length - 2] < 4000001) {
  fib.push(fib[fib.length - 1] + fib[fib.length - 2]) 
  totalElements = totalElements + 1;
  }
}

document.write(fib);
console.log(totalElements);

var evenTotal = 0;

for (var i = 0; i < totalElements; i += 1) {
  if (fib[0] % 2 === 0) {
    evenTotal = evenTotal + fib[0];
    fib.shift();
  }
  else {
    fib.shift();
  }
}

console.log(evenTotal);

Okay, I like that much better than the solution with the random "100" inserted in.  Well, from that, I worked on a cleaner solution:

var fibArray = [1,2];
var total = 2;

for (var i = 0; i < fibArray.length; i += 1) {
  var fib = fibArray[fibArray.length - 1] + fibArray[fibArray.length - 2];
  if (fib < 4000001) {
  fibArray.push(fib);
  }     
  if (fib % 2 === 0 &&  fib < 4000001) {
    total = total + fib;
  } 
}

document.write(fibArray)
console.log(total);

When running this code, the first if statement is true 30 times, the second if statement is true 10 times, and the loop itself runs 32 times.  However, on the 31st loop, we do have a new value for fib, but it becomes a standalone value because no new fib is pushed, as the first if statement does not activate (neither does the second, as the number is odd, but if it were even, it would activate, and this would cause a problem, as a number like 4,000,002 would go past the first if statement, but trigger the second, so to fix this, I added fib < 4000000 to the second if statement as an additional condition).  I can also add - 1 to the second section of the loop condition, and that gets us down to 31 loops, with the end result being the same (the fib variable becomes the first Fibonacci number over 4,000,000, but does not get pushed to the array, and so, it remains the same on every iteration after that one), but I decided to move along from this problem for now, as that code above is much cleaner that my prior attempts.  It's like a synthesis of the best of my first and second solutions.  I'm stoked that I finally came up with a solution where I don't have to know the number of iterations ahead of time in order to solve the problem.  I've learned quite a bit, and I'll come back to this problem later once I've learned some new things.

So, Chapter 18 goes over "for" loops.  This is an example of a simple way to iterate through an array, via the use of a "for" loop, coupled with an "if" statement:

var city = prompt("What is one of the cleanest cities?");

var cleanestCities = ["Cheyenne", "Santa Fe", "Tucson", "Great Falls", "Honolulu"];

for (var i = 0; i <= 4; i += 1) {
  if (city === cleanestCities[i]) {
    alert("Good job!");
  }
}

The i <= 4 in the for loop means the loop will iterate until i is less than or equal to 4.  Since the first loop has I set at 0, that gives us one extra loop, for a total of 5 loops, equaling the 5 elements in the array.  You can decrement and use negative numbers, for example this loop:

for (var i = 0; i > -3; i--) {

Runs three times and decrements by 1 each time.  It starts at 0, goes to -1, then -2, then it can't run a third time because -3 is not less than -3.  

Chapter 19 then goes over "for" loops on more detail, going into flags, booleans, array length, and "loopus interruptus," as the author calls it.  I learned about flags, where we set a variable to default to false (or true), and then if a condition is met, we change that variable to true (or false), but if not met, the flag/variable remains false and another statement runs.  I also learned about the "break" keyword which can be inserted after a line of code when we want to prevent further iterations from running, for example if an answer was found on a 3rd loop, but the computer was set to run 8 loops, the "break" keyword would prevent the loop from continuing once it's no longer necessary for it to do so.  Here's an example of a flag:

var matchFound = false;

The false is a boolean value (the other is true).  So we have this variable default to false, then switch to true when certain conditions are met, and if they aren't, it remains false and triggers some other conditions.

Chapter 20 goes over nested for loops.  I finished Chapter 20 and stopped there because I don't think the things I am learning will prepare me enough for the test.  I thought they would, but that's not the case so far, so I've got to change course.  

I am going back to the modules starting tomorrow, starting where I left off, and continuing from there until I finish the modules.  Once I finish the modules, I will take the test for the Viking School, in Ruby.  I could take the test right now in JavaScript, but I think my odds of passing it are much higher if I take it after going over the material provided by the Viking Code school itself, instead of by going over an unrelated JavaScript book.

Nonetheless, I got quite a bit of work done these last couple of days, a total of 20 hours of coding.

SUMMARY OF CODING SKILLS

Total Treehouse Points: 5,385

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

Treehouse Ranking (%): "You have more total points than 94% 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 56)
In Progress: "A Smarter Way to Learn Javascript," by Mark Myers (on pg 72)

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 Since Last Entry: 20
Total Hours Coding: 441

No comments:

Post a Comment