Monday, March 2, 2015

Day 78: Head First Javascript and Treehouse Arrays Course

An array is a data structure, in other words, it's a way to store and organize information.  An array can hold a single string, 50 numbers, or any combination of data types, including strings, numbers, booleans, and other arrays.  We create an array like so:

var myCoolArray = ["orange", "apple", "coconut", "banana"];

This can also be expressed like so:

var myCoolArray = ["orange", 
"apple", 
"coconut",
"banana"]; 

White spaces are fine in javascript.  When locating items in an array, the first item is indexed as 0, the second as 1, and so forth.  So, to log the "orange" string, I would do this:

console.log(myCoolArray[0]);

I've made a lot of changes to my work area lately.  I purchased a comfortable office chair for a little over $200.  My previous office chair broke several months ago and I threw it away, and since then, I had been using a foldable metal wal-mart chair, but the problem was that every 15 to 20 minutes or so, it would make my legs hurt, as it would cut off their blood flow by putting pressure on my upper thighs.  This was not good, but I just compensated by studying at coffee shops most of the time.  I did that until I decided that I needed to invest in a good chair.  So I tested out over 50 chairs at various stores, until I found one that fit my body perfectly.  I'm happy to say that since I purchased that chair, my studying has increased dramatically.  I also bought a plastic mat so that the chair can roll around easily on the carpet.  This investment in ergonomics has been extremely worthwhile, and I wish I had done it sooner.  

I also just placed an order for a laptop stand because I am tall, and currently, my neck is at an awkward position whenever I look at my macbook's screen.  It's fine when I look at the second monitor, but not when I have to look down at the macbook.  Even as I type this, my neck is uncomfortable, because I keep the blog on the macbook screen and the work I'm currently working on on the second monitor.  The laptop stand has excellent reviews, including some from other tall people which praise its performance in regards to ameliorating neck strain.  Although these kinds of topics don't really come up when discussing learning how to code, they're actually extremely important, and I just wish I had realized it sooner.  As a developer, we need to be aim for optimum ergonomics in order to prevent short term fatigue and long term health problems.

Back to arrays!  We used the .length property will output the number of letters in a string or the number of items in an array, for example.  After lots of playing around, I entered this code in Codepen, which I started using again today:

var numbers = [1,2,3,4,5,6];
numbers[numbers.length] = 3;
document.write([numbers.length]);

document.write(numbers[6]);

The output is:

73 

So let me explain how we ended up with an output of 73.  The first line of code creates the array.  The array has 6 items within.  The first item is the number 1, and it has an index value of 0.  The last item is the number 6, and it has an index value of 5.  Now, the second line calls the array, then adds an item at the end of the array, and that item is the number 3.  So, at this point, the number three is the 7th item in the array, which has an index value of 6.  Now, the third line in the code calls length of the array (and displays it on screen via calling the .write method on the document object), which is 7, because there are 7 items in the array now (we added the 7th item, 3, which has an index value of 6).  The final line of code calls the item in the numbers array with an index value of 6, which is 3, because the 7th item in the array is 3, and 3 has an index value of 6.

Neat!  It took me a bit of playing with the array to get a hang for that.  Hopefully that wasn't too confusing.  You can use the .push method to add an item or items to the end of an array.  Like so:

numbers.push("teacup");

The code above would result in (adding to the prior example):

var numbers = [1,2,3,4,5,6,3,"teacup"];

The .push() method also returns the length of the array.  The opposite, the method to add an item or items to the beginning of an array, is the .unshift method, which has an odd name.  The .pop() method "pops" the last item in an array off.  While it does this, it also returns that item, so you can save the item by creating a variable like so:

var lastItem = numbers.pop();

In that case, lastItem would hold the number 3, as that was the last item in the array.  The .shift() method is like the .pop() method, except it removes (and returns) the first item in an array.  As an aside, properties like .length do not require parentheses after the property, but methods like .pop() do.  There are nearly two dozen array methods.  The .join() method takes an array and returns a string with all the items in an array separated by a supplied character such as a comma or colon.  Like this:

numbers.join(", ");

Would return the contents of the array, separate by a comma and a space (the comma and the space will appear after each item in the array except for the last one).  The .concat() method will return the result of the array it is called on with the array inside the parentheses added after the other array, but it does not actually change either array.  The next method is .indexOf(), which will return the index number of the item that you enter into the parentheses, if the item is found in the array.

The class recommended that, in regards to working on projects, we code, then test the code before moving on, then code some more, test the code before moving on, and so on and so forth.  This technique is helpful in catching errors.  This is some of the code we worked on:

var inStock = [ 'apples', 'eggs', 'milk', 'cookies', 'cheese', 'bread', 'lettuce', 'carrot', 'broccoli', 'pizza', 'potato', 'crackers', 'onion', 'tofu', 'frozen dinner', 'cucumber'];
var search;

function print(message) {
  document.write( '<p>' + message + '</p>');
}

while (true) {
  search = prompt ("Search for a product in our store.  Type 'list' to show all of the produce and 'quit' to exit");
    search = search.toLowerCase();
  if ( search === 'quit') {
    break;
  } else if ( search === 'list') {
    print( inStock.join(", ") );
  }
    else {
      if ( inStock.indexOf( search) > - 1) {
        print( "Yes, we have " + search + " in the store.");
      }
      else {
        print( search + " is not in stock.");
      }
    }

}

It's a shopping/grocery store program which uses prompts to check on inventory.  When accessing arrays within arrays, the format is like so:

myArrayName[3][4];

The three corresponds to the index value of item in the array (in this case also an array), and the 4 corresponds to the index value of the item inside of the array inside of the array.  This is called a two dimensional array.  The class continues with an assignment to build a quiz using two dimensional arrays and the prompt() method, but I will set things down for now.  I had a very productive day, now I'm going to enjoy a show or movie in bed while I mull over the quiz in the background of my mind.  Tomorrow will be a great day, I'm looking forward to waking up early and solving the next challenge!

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)

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: 5.5
Total Hours Coding: 375.5

No comments:

Post a Comment