JS 102 - Data Structures

['hip', 'hip']
A hip hip array
  1. Arrays

    An array is a set of individual things. It's a list. A collection. A grouping.

    Creating an array

    Creating an array is quite easy in javascript:
    //an empty array
    var foo = []
    But creating an empty array is pretty boring. We generally want content inside of it.
    var foo = ['cool', 'beans']

    Accessing data in an array

    In this example, we've created an array with two things in it. The first thing is a string 'cool', the second one is a string 'beans'.
    We can reference each of these by asking the array for the object at a certain position:
    foo[1]
    'beans'

    Pop Quiz!

    Why did it return 'beans' when we asked for the value at position 1, but beans is the 2nd value in the array?
    Because computers start counting at 0, not at 1. 
    Position 0 is the 1st position. 
    Position 1 is the 2nd position.

    Things arrays can store

    Arrays can store anything:
    var foo = [1, 'asdf', false]
    typeof(foo[2])
    boolean
    They can even store other arrays:
    var foo = [1, 'asdf', false]
    var bar = [foo, 8, 'qwerty']
    typeof(foo[0])
    object
    typeof(foo[0][2])
    boolean
    Note that the first output in the example above was `"object"`. That's because everything in javascript that isn't a primitive (number, string, boolean, or function) is considered an object. Be careful when using `typeof` checks for non-primitives.
    Much like the string's `replace()` function, arrays have methods that can be called on them as well as some inherent values.
    var foo = [1, 2, 3]
    foo.length
    3
    //push will add a value to an array
    foo.push(4)
    foo
    [1, 2, 3, 4]
    foo.length
    4
    The `.length` attribute will let us know how many elements are inside an array. This is especially valuable as you'll see in the next section.
  2. Loops

    One of the biggest advantages of automating things is we can repeat the same function on every piece of data we have. To do this we use a loop. A loop in javascript is fairly easy:
    for(var i = 0; i < 5; i++){
      //log the value i to the console
      console.log(i)
    }
    0
    1
    2
    3
    4
    Let's walk through the syntax one step at a time. First off, the for loop takes three arguments: the start, the condition to end, and the incrementor. The start is
    var i = 0;
    This is our initial counter. We'll be using the variable i to decide when to stop looping, as well as in the loop itself to know how many time's we've looped through already. The condition to end is:
    i < 5;
    As soon as i is greater than or equal to 5, the loop will stop firing. Keep in mind this check is made *before* the loop runs, so the loop will not run if the statement evaluates to false. The last bit is the incrementor:
    i++
    This is ran after each iteration of the loop. Incrementing by one is pretty standard, but theoretically you could put any statement there.

    Looping through data

    With this format it becomes very easy to loop through an array:
    var rickroll = ['Never', 'Gonna', 'Give', 'You', 'Up']
    for(var i = 0; i < 5; i++){
      //will output the value of foo and index i
      console.log(rickroll[i])
    }
    "Never"
    "Gonna"
    "Give"
    "You"
    "Up"

    Dynamic loops

    Note that we had to hard code the number to stop at. This is called a static loop, or in other words a loop that runs a fixed number of times. What if we didn't know how large our array was, or if the size was dynamic? What would we do in the comparison to make the loop iterate through every value of an array?
    var jokes = ['Why do Marxists only drink herbal tea?', 'Because all proper tea is theft']
    for(var i = 0; i < jokes.length; i++){
      console.log(jokes[i])
    }
    "Why do Marxists only drink herbal tea?"
    "Because all proper tea is theft"
  3. Objects

    Arrays can also store functions, but it's usually not a great idea. The reason why is arrays are non-descriptive of their contents. If I were to call foo[0]("asdf") it'd be non descriptive of what the function actually does. In general the more readable your code is, the better it is. Which is why we have Objects.
    While an array is technically an object from javascript's point of view, when we talk about objects we're usually referring to a different construct. A loose definition of an object is that it's a variable that has methods attached to it. Let's jump in rather than going through the theoreticals though.
    var person = {
      name: 'John',
      age: 30,
      gender: 'Attack Helicopter'
    }
    If we want to know that John sexually identifies as an attack heliocopter, we can check by calling
    person.gender
    "Attack Helicopter"

    Object functions

    Objects can also have functions. Storing functions within objects is generally preferable to keeping them off on their own, as it allows for better organization.
    var person = {
      name: 'John',
      age: 30,
      gender: 'Attack Helicopter',
      haveBirthday: function(){
        person.age = person.age + 1
      }
    }
    
    person.age
    30
    person.haveBirthday()
    person.age
    31
  4. Exercises

    Write a function named fizzbuzz. Make it run a loop that outputs the numbers 1-100. If the number is divisible by 3, output fizz. If it's divisible by 5, output buzz. If both, output fizzbuzz. Otherwise, output the number.

    *hint* remember that you can use % to check if a number is divisible by another
    fizzbuzz()
    1
    2
    fizz
    4
    buzz
    fizz
    //...
    14
    fizzbuzz
    var fizzbuzz = function(){
      for(var i = 1; i <= 100; i++){
        if(i % 3 == 0 && i % 5 == 0){
          console.log('fizzbuzz')
        }
        else {
          if(i % 3 == 0){
            console.log('fizz')
          }
          else {
            if(i % 5 == 0) {
              console.log('buzz')
            }
            else {
              console.log(i)
            }
          }
        }
      }
    }
    

    Make an object named turtlePower. Give it the following:

    • An attribute named lyrics that stores the lyrics of the Teenage Mutant Ninja Turtle theme song.
    • A method named singLine(n) that outputs the nth line of the theme song
    • A method named sing() that outputs the full song in sequence
    Be sure to use console.log() for the output, not alert.
    turtlePower.singLine(3)
    "Heroes in a half shell"
    turtlePower.sing()
    
    "Teenage Mutant Ninja Turtles"
    "Teenage Mutant Ninja Turtles"
    "Teenage Mutant Ninja Turtles"
    "Heroes in a half shell"
    "Turtle Power"
    "Here we go its the"
    "Lean green ninja team"
    "On the scene"
    "Cool teens doing ninja things"
    "So extreme"
    "Out the sewer like laser beams"
    "Get rocked with the"
    "Shell shocked pizza kings"
    "Cant stop these radical dudes"
    "The secret of the ooze"
    "Made the chosen few"
    "Emerge from the shadows"
    "To make their move"
    "The good guys win"
    "And the bad guys LOSE!"
    var turtlePower = {
      lyrics: [
        "Teenage Mutant Ninja Turtles",
        "Teenage Mutant Ninja Turtles",
        "Teenage Mutant Ninja Turtles",
        "Heroes in a half shell",
        "Turtle Power",
        "Here we go its the",
        "Lean green ninja team",
        "On the scene",
        "Cool teens doing ninja things",
        "So extreme",
        "Out the sewer like laser beams",
        "Get rocked with the",
        "Shell shocked pizza kings",
        "Cant stop these radical dudes",
        "The secret of the ooze",
        "Made the chosen few",
        "Emerge from the shadows",
        "To make their move",
        "The good guys win",
        "And the bad guys LOSE!",
      ],
      singLine: function(n){
        console.log(turtlePower.lyrics[n])
      },
      sing: function(){
        for(var i = 0; i < turtlePower.lyrics.length; i++){
          turtlePower.singLine(i)
        }
      }
    }