JS 101 - My First Coding Lesson

"Java is to JavaScript what Car is to Carpet"
Chris Heilmann
  1. What is javascript?

    HTML defines the content of a web page.

    CSS defines the style and layout of a web page.

    Javascript defines the behavior of a web page

    When you click a button and a modal popup appears, that's javascript responding to your mouse click. When you type "@jurge" in confluence and it comes up with a name picker, that's javascript listening to your keystrokes. Almost all interaction on a page is handled via js.

  2. What javascript is *not*

    Java. They're completely different languages only bound by the individual creators' affinity for coffee.

    Easy. Buckle up kiddos.

  3. Variables

    In javascript, a variable is a container. It can hold a value, or a bit of text, or complex objects. Everything in javascript is a variable - this is important, keep it in mind for later as it will help things make sense when we get to the more advanced stuff.

    Defining a variable is easy:

    var foo = 3

    Let's walk through this simple statement step by step.

    *var* foo = 3

    The var declaration means we're creating a new variable. This is only used the first time you create a variable, afterwards you can reference it simply by calling the variable's name:

    var *foo* = 3

    The name in this case is 'foo'. This is the name that we'll reference the variable by later on.

    var foo *= 3*

    The last part is our assignment. We're assigning 'foo' to be equal to the number 3. Now whenever we reference 'foo', we're actually just saying '3'.

    Interactive time!

    Rather than just list documentation, let's get interactive! Right click on this page and select 'inspect'. This will bring up the DOM inspector that you should be familiar with at this point. One thing you probably haven't used in it yet is the javascript console:

    Click the 'console' tab at the top. Here we can interact dynamically with the page using javascript. Don't worry, you wont break anything. Javascript is only ran on the client side, not on the server. If you break something on the page while fiddling, just refresh the page.

    Go ahead and type

    var foo = 3

    And press enter to run the command.

    The first thing you'll notice is the console will say:

    var foo = 3
    undefined

    The 'undefined' part is the response from the command, or in javascript's terms, it's 'return' value. Remeber that programming at its core is the manipulation of inputs and outputs. The input here was 'var foo = 3', and the output was 'undefined'. The reason why it's undefined is we're simply making an assignment, we're not asking for that assignment back just yet. If we wanted to get that assignment back, we can just type this in the console:

    foo

    What you should see now is the input (foo) along with the output (3)

    foo
    3
  4. Numbers and math operators

    While setting a variable to 3 is toats exciting, generally we want to manipulate numbers as well. In javascript, we have the following operators when it comes to numbers:

    Operator Description Example
    + Addition foo = 5 + 6
    - Subtraction foo = foo - 2
    * Multiplication foo = foo * 2
    / Division foo = foo / 3
    % Mod foo = foo % 5
    ++ Increment foo++
    -- Decrement foo--
    Pop Quiz! If you were to run all of the examples in sequence, what would the result be?
    ###########
    #    1    #
    ###########
  5. Strings

    <-- not those strings

    A string in programming is a string of characters in sequence, or in other words any text you see. If I loaded the contents of this paragraph in javascript, it would be a string:

    var paragraph = "A string in programming..."
    typeof(paragraph)
    "string"

    Strings are one of the three primitive data types in javascript (the others being numbers and booleans). Primitives are the basic building blocks of js. In prototyping we end up doing a lot of string manipulation. In most programming languages, there are ways to join two strings together (concatenation), replace specific parts of strings, and many other functions. We'll go over a couple of the most important ones you'll need, but keep in mind this is just scratching the surface.

    Joining strings

    "foo" + "bar"
    "foobar"
    Concatenation is one of the easiest things to do with strings. You can actually use the + symbol to do it, just like you would with numbers. Keep in mind + is the only operator that works on strings, the other numerical ones will throw an error.
    "foo" + 3
    "foo3"
    "foo" + 3 + 4
    "foo34"
    3 + 4 + "foo"
    "7foo"
    "foo" + 4 / 2
    "foo2"

    Curiously, we can also add numbers to strings. Keep in mind though that this leads to some wonky behavior. The number will either be treated like a string, or a number, depending on how javascript feels that day.

    Mixing numbers with strings is not to be trusted.

    String replacement

    Congrats, it's time to learn how to use your first function: replace()

    Replace is pretty straight forward, it replaces a part of a string with another part. The syntax (how the command is constructed) is fairly straight forward:
    myString.replace('old part', 'new part')
    
    Let's see it in action
    var deepThoughts = "I think Jake is the best prototyper"
    deepThoughts.replace('Jake', 'Kirsten')
    "I think Kirsten is the best prototyper"
    Luckily js thinks this statement is bs and hasn't actually saved the value into the variable. Even though the output was "I think Kirsten is the best prototyper", if we invoke deepThoughts now we'll see something different:
    deepThoughts
    "I think Jake is the best prototoyper"
    The reason is that replace() doesn't modify the string it's called on. Rather it returns an entirely new string with the modified values. This is important because sometimes we simply want the output, but to keep our variables intact. A good example of this is a marketing email. Say we had the following email and we were sending it to a thousand users:
    var emailTemplate = "Hello {user}, your bill is due."
    Since the string doesn't update, it only returns a new value, with our template we could do the following:
    //note that sendEmail() is pseudocode, but assume it sends an email 
    //magically without needing an email address, just the content
    
    sendEmail(emailTemplate.replace("{user}", "Frank"))
    
    With that in mind, if we *did* want to update the deepThoughts variable from the example above, how would we do it?
    deepThoughts = deepThoughts.replace('Jake', 'Kirsten')
    
  6. Booleans

    True or false. 1's or 0's. That's all a boolean is. At their core, every computer is just series of true or falses in a row. Knowing how to manipulate them using boolean operations is critical to adding logic to your app. First though, let's look at how javascript evaluates booleans.

    Declaring a boolean is simple:
    var foo = true
    foo
    true
    var bar = false
    bar
    false
    Interestingly, in javascript every variable is either true or false, regardless of its data type. Some strings are true, some strings are false. Some numbers are true, some are false. We'll dive into why that is once we're deeper into javascript, but for now let's just explore which ones are true and which ones are false. The function
    Boolean(INPUT)

    Will let us evaluate whether the input is true or false. Test some of these out in the console as well:

    Boolean(1)
    true
    1 is considered true
    Boolean(0)
    false
    0 is considered false
    Boolean(-1)
    What do you think -1 is? Try it out now

    As you've noticed, any number except 0 is true. This is usually the norm - most things are true (javascript evaluates having content as true), with certain exceptions being false.

  7. Strings

    Boolean("")
    false
    An empty string is considered false
    Boolean("Brett Kavanaugh is a great choice for a Supreme Court Justice.")
    true
    Any string with one or more characters in it evaluates to true, even if the statement itself isn't

    The fact that strings and numbers can be true or false makes it very easy to set up logic rules in javascript using what's called an if statement.

  8. If statements

    if(true){
      // do some stuff
    }
    
    if(false){
      //don't do stuff if it's false
    }
    
    If statements can also have an else statement, which triggers if the evaluation part of the if statement is false:
    if(foo){
      // if foo is true, do this
    }
    else {
      // if foo is false, do this
    }
    
    
    We can use if statements to create simple logic. Check the example below for instance. If you type something, it makes a popup with that content. If the input is empty however, the string evaluates to false and it instead pops up a different message. Try it out:
    The source uses some things that you aren't familiar with yet, but you can see where the if statement is used:
    //find the #ccDemoButton element and listen for any click events
    document.getElementById('ccDemoButton').addEventListener('click', function(){
      //get the value of the input field
      var inputValue = document.getElementById('ccDemoInput').value
    
      //if the input has content, make a popup with that content
      if(inputValue){
        alert(inputValue)
      }
      //otherwise tell the user they suck
      else { 
        alert('you gotta type something brah')
      }
    })
  9. Comparisons

    Often times however we don't want to simply check and see if a number is zero or a string is empty, we want to make a comparison. To do this, we have an entirely new set of boolean logic operators:

    Operator Description Example
    == is equal to
    5 == 4
    false
    === is *really* equal to Examples for another time :)
    <, > Less than, greater than
    3 < 5
    true
    <=, >= Less than or equal to, greater than or equal to
    3 <= 3
    true
    & Logical and. Outputs true only if both sides of the & statement are true.
    true & true
    true
    true & false
    false
    | Logical or. Outputs true only if any of the sides of the & statement are true.
    true | true
    true
    true | false
    true
    &&, || Short circuit logical and, short circuit logical or. With && it stops evaluation of the statement as soon as a false is found. With || it stops as soon as a true is found.
    5 < 7 & 4 < 2 & alert("hi")
    false
    5 < 7 && 4 < 2 && alert("hi")
    false, doesn't trigger the alert
    ! Inverse. Changes the day to opposite day.
    !true
    false
    ! 4 < 2
    true

    Complex if statements

    Using these comparitors, we can create more complex if statements. For example:
    var money = 3
    if(money < 5) {
      alert('not enough money to make a purchase')
    } 
    else {
      money = money - 5
    }
    
    We can also check and see if a number is in a range by stringing statements:
    var speed = 55
    if(speed < 45 || speed > 65){
      alert('you suck at maintaining speed. All the cars hate you. Have you heard of a thing called cruise control?')
    }
    else {
      alert('nice driving bro')
    }
  10. Functions

    A function is a command that takes inputs and produces outputs. For example:
    var addOne = function(n){
      return n + 1
    }
    
    This defines a function called "addOne", which takes an input (n), adds one and returns it. We can call this function now that it's defined:
    addOne(4)
    5
    Remember that variables can store anything in javascript, even functions as shown above. We can however use a shorthand version of the function definition as well:
    function addTitle(name){
      return "Professor " + name
    }
    addTitle("Jake")
    "Professor Jake"
    Functions can also take in multiple inputs:
    function addNumbers(n1, n2){
      return n1 + n2
    }
    addNumbers(3, 8)
    11
  11. Exercises

    • Write a function named isEven() that inputs a number and outputs true if it's even and false if it's odd
      isEven(2)
      true
      isEven(381)
      false
      var isEven = function(n){
        if(!n % 2) {
          return true
        }
        else {
          return false
        }
      }
    • Write a function named repeatString() that inputs a string and outputs that string repeated twice.
      repeatString('asdf')
      "asdfasdf"
      var repeatString = function(s){
        var newString = s + s
        return newString
      }
    • Write function doBoth() that inputs a string or a number. If it's a number, call isEven() on it. If it's a string, call repeatString() on it.
      doBoth('asdf')
      "asdfasdf"
      doBoth(4)
      true
      *hint*: the typeof() function will return the type of a variable. Use in conjunction with == in your if statement.
      var doBoth = function(input){
        if(typeof(input) == 'string'){
          return repeatString(input)
        }
        return isEven(input)
      }