---
# System prepended metadata

title: TINKER - Javascript Part I_Group 3
tags: [' tinker', ' js', mstu5003]

---

---
tags: mstu5003, tinker, js
---
# TINKER - Javascript Part I_Group 3

Group members:
Regina Wright
Sally Ng
Sandra Sowah
Ze Lu

See demonstration: https://codepen.io/jmk2142/pen/eGZRME

:::info
**README:**

At the bottom (after the tinker activities) there is a [**NOTES**](#NOTES) section with a text-based conceptual explanation of many of the things going on here. My recommendation:

- Play with the interface to get a sense of what it does.
- Look at the Tinker Tasks and code first to get a sense of the context.
- Read the NOTES as it will arm you with ideas to approach the tinker task/problems.
- Then try the tinker problems.
:::

## Tinker Tasks

This tinker takes the basics of what you learned about variables, functions, arrays, and puts it in a real context of web-pages. This is our first foray into actual user-computer interaction. As a general rule of thumb, at the very least, for every section/part you should be thinking:

> What is the STATE?
> What is the SEQUENCE?
> What is the CAUSALITY?

In your groups - try to articulate these line by line, part by part. Articulation should be _out loud_ or _in writing_. It's very important that you do this outside of your head.


### Part 0 - Warmup - [Definitely Maybe] - Ze (https://youtu.be/TDe1DqxwJoc)

> Jimmy asks, Sally... will you go to the prom with me?
> [Sally](https://youtu.be/cmpRLQZkTb8?t=1m10s) handwrites the following reply back.
```javascript=
function yes(x){
  return x();
}
function no(x){
  return 'yes';
}
function maybe(no){
  return no;
}
var definitely = maybe(yes(no));
```
**Inputs and Outputs** - Try to mentally solve the problem first (using pen and paper OKAY.) Then try it to see the actual answer. Then adjust your answer accordingly.
- What do you think is the value of `definitely`?
  - Is Jimmy going to the prom with Sally?
:::info
**Answer:** 
Yes, Sally is going to the prom with Jimmy. 
:::
- How does this work? (Code, not relationships.)
:::info
**Answer:** 
Let's first look at the function yes, the yes function returns the return value of the function with the parameter as the reference of the function name. In this case, it will return function no(). Function no will return string 'yes' regardless what parameter is put in to the function. Therefore, yes(no) will return what no(x) returns, which is 'yes'. Function maybe() returns the value of the parameter. In this case, it will return the string 'yes'.
:::
- When is the `no` function called?
:::info
**Answer:** 
The no function is called on line 10. When maybe is called, the parameter yes(no) is put in. 
:::
- On the line `var definitely = maybe(yes(no));` there aren't ()s immediately after `no`. What is the significance of this?
:::info
**Answer:** 
As the yes function takes the parameter as the reference of the function, not the function itself. Therefore, only "no" is put in, not no().
:::
- Explain how this code snippet works, line by line, part by part.
  - Be very specific
  - Use important keywords
  - Provide explanation of what each syntax detail represents as well
:::info
**Answer:**
Create the function with name called yes. Function yes will take parameter x, and it will execute function with name the same as the value of x and return the result of that function. Create the function no. Function no will take parameter x, however, no matter what parameter is given, it will always return 'yes'. Create the function maybe. Function maybe will take parameter no, and it will return the value of the given parameter. Then we create a variable called definitely. We assign the value with maybe(yes(no)). Inside the function yes, it will execute the fucntion no, which will return 'yes'. Then yes(no) returns value 'yes'. Then maybe function will return the 'yes'.
:::

**Template Literals** - Backtick symbols `` ` `` in JS are different than single-quotes `'` and double-quotes`"`. They are used to make what is called, `template literals`.
```javascript
var x = "bitter";
var y = "sweet";
var z = `Coffee is ${x}, Sugar is ${y}, Monday mornings are ${x}${y}.`;
var n = "Coffee is " + x + ", Sugar is " + y + ", Monday mornings are " + x + y + ".";

// z and n end up being the same values after the String is resolved.
// "Coffee is bitter, Sugar is sweet, Monday mornings are bittersweet."
```
- What does the `${}` syntax represent?
:::info
**Answer:**
The syntax ${} represents the embedded value of what's put in the {}.
:::
- Why are template literals super useful for us?
:::info
**Answer:**
It's important and commonly used for string interpolation, it makes string formatting clear.
:::


### Part 1 - Ze

:::info
**Parts 1-4: Breaking it Apart**

It might help to start by forking the codepen into four separate pens. And for each pen, reducing/removing all unused code, i.e. both HTML and JS for that part, so that all that remains are the functional ones for that part to work. (There is a reason why I don't do this for you...)

Reducing what is visually in front of you can greatly help you to focus on the bits that are relevant to the sub-problem at hand.

Note that `printLog()` is utilized across multiple parts.
:::

- Click on the link at the top to view the `index-simple.html` version. Compare the HTML between this version and the Bootstrap version. Compare the JS between this version and the Bootstrap version.
  - How do these two versions compare with regard to helping you understand Javascript?
      :::info
      **Answer:**
      Javascript provides dymanic feature for web applications. Bootstrap provides a framework to make the web development easier and faster.
      :::
- Play with the interface (each of the buttons) and observe how the program reacts. When tinkering, try changing the order in which you play with the interface. Take note of the printed _history_.
  - Explain how this program works with regard to STATE, SEQUENCE, and CAUSALITY of each line, and/or specific parts of a line as appropriate. Use specific vocabulary, as demonstrated in the notes section.
    - Be sure to articulate both aspects of the HTML and JS.
    - What does the `prompt` function return?
    :::info
    **Answer:**
    The prompt function pops up a dialog box that allows users to input the information.
    :::
    - Explain what you think the `document.querySelector()` does. Talk about this in terms of the functions vocabulary presented in the Notes.
    :::info
    **Answer:**
    It's used to select the element object that we want to work on. 
    :::
    - If I told you that `document.querySelector` RETURNS something, what do you think that something is?
    :::info
    **Answer:**
    It will return the selected element object. If there is not match, it will return null. 
    :::
  - How could you alter the `printName` function in order to print the users first and last name in the browser window tab?
      :::info
      **Answer:**
      ```javascript
      function printName() {
          var fullName = firstName + " " + lastName;
          //document.querySelector('#fullName').textContent = fullName;
          document.title = fullName;
          printLog('#prePartOne', `printName called(): ${fullName}`);
      }
      ```
      :::
  - How would you use the `makeFullName` function to shorten the `greetUser` and `printName` code?
  
  :::info
  **Answer:**
  ```javascript
  function greetUser() {
      alert("Hello " +  makeFullName(firstName,lastName) + "!");
      printLog('#prePartOne', `greetUser called(): ${displayName}`);
  }
  function printName() {
      document.querySelector('#fullName').textContent =  makeFullName(firstName,lastName);
      printLog('#prePartOne', `printName called(): ${fullName}`);
  }
  ```
  :::

### Part 2

- Play with the interface (each of the buttons) and observe how the program reacts. When tinkering, try changing the order in which you play with the interface. Take note of the printed _history_.
  - Explain how this program works with regard to STATE, SEQUENCE, and CAUSALITY of each line, and/or specific parts of a line as appropriate. Use specific vocabulary, as demonstrated in the notes section.
    - Be sure to articulate both aspects of the HTML and JS.
:::info
**Answer:** 
Without any input, the program is in its "zero state." The text input boxes display the default text of "username" and "email". Once the input is entered, the state changes and username/email are assigned the value (or variable?) of that input. (i.e. Ginabina and Ilovetacos26@gmail.com). The print(log) changes to display this assignment. Once the user clicks "print info" the state of the program changes again to display the new values (variables?)that are assigned to "username" and "email" in the heading that greets the user. 

The sequence that occurs is that when the user types text into the input boxes the functions `updateEmail` and `updateUsername` are called with the`event`data (user input?) passed in as argument. The routines `updateEmail` and `updateUsername`start.
      -The HTML placeholder is replaced with the input that triggered the `event`. 
      -`username` and `email` are set to the text through the value property of `email` and `username` 
      -`updateEmail` and `updateUsername`end
When the user clicks the "Print Info" button
      -a click event is triggered 
      -`printInfo()` function is called
      -`printInfo` routine starts
        -`username` and `email`state is the user text and is displayed in the greeting heading as well as the printLog "history" box. 
    -`print info` routine ends
Entering input into the input boxes of "username" and "email" causes those fields to update from the HTML `placeholders` because they are no longer `undefined`. Clicking the "Print Info" button causes that input to be displayed in the greeting title replacing the HTML placeholder text of "unknown text". 
Clicking the "Reset" button returns the program back to its zero state through the  value property of `#prePartTwo` .
:::

 - What kind of events are happening in Part 2 and explain how this relates to when the handlers will run.
    - What is `event.target`?
    :::info
    This returns the element that triggered the event. So in example for `updateEmail` the text entered (the email?) that triggered the event is returned. The same is true/similar for the `event.target` of the other functions (`updateUsername` etc.)

    :::

    - What does the dot `.value, .textContent, .innerHTML` represent in this context?
     :::info
     The properties or functions related to to these objects. So, a connection to the value, text, or HTML properties that need to be accessed. So they all represent properties of an element.
     :::
    - Why does `updateEmail` have a parameter for `event` data but the other functions do not?
    :::info
    Because it is passing the event information into the function. Although we are not passing the information in the other functions we still can, but we are defining it in the `updateEmail` function with the `event` parameter.
    :::
    - `resetInfo` is actually a little broken. Why?
:::info
Because it doesn't actually reset the values of the username and email, it just removes their appearance. But if you click the "Print Info" button you can see the values reappear. 
:::



### Part 3

- Play with the interface (each of the buttons) and observe how the program reacts. Take note of the printed _INFO_.
  - Explain how this program works with regard to STATE, SEQUENCE, and CAUSALITY of each line, and/or specific parts of a line as appropriate. Use specific vocabulary, as demonstrated in the notes section.
    - Be sure to articulate both aspects of the HTML and JS.
:::info
**Answer:** 
* This section's HTML begins with an image that is a child of a parent "div" with the "id" "animalImageParent." Then, below that, is a grid system with bootstrapped "button" elements. Each button has a unique javascript "function" that is called when the button is "on clicked." 
* In JS ShowImageData(), ShowParentData(), and ShowButtonData() are the first types. By choosing the "id"s of either the "image," "div," or the current event that is being targeted, their purpose is to "print" out the information of the element.
* The following command, "changeImage," creates a variable called "imgEL" and assigns it to the HTML tag #animalImage. It then assigns a src to a fresh image, "imgEl." Thus, when this function is invoked, the src of the #animalImage will be changed to a new one that is written in JS.The final function, "resetPartThree," first returns the src of the #animalImageData to its original HTML value. Then it transforms the #prePartThree's innerHTML into INFO, which will appear as INFO on the screen.
:::

  - Compare and contrast the `showImageData` and `showImageViaParent` functions.
    - How do these two different functions achieve the same output?
:::info
**Answer:**
* `showImageData`: Searching the animalImage using classname
* `showImageViaParent`: First searching its parent animalImageParent, and then access the child of it, which is exact the element of animalImage
:::
  - Compare and contrast the `showParentData` and `showParentViaImage` functions.
    - How do these two different functions achieve the same output?
:::info
**Answer:**
* The `showParentViaImage` is for searching the data using exact classname, while the`showParentData`is first finding its parent, then access its child.
::: 
  - Can you modify the related code so that each time you pressed it, it would show 1 of 5 images, cycling through to the next image per click?
    - There are several ways to solve this.
:::info
**Answer:**
```javascript
function changeImage() {
	var imgEl = document.querySelector('#animalImage');
	imgEl.src = ["http://i.imgur.com/0JOTJaG.gif","http://i.imgur.com/4AiXzf8.jpg","http://i.imgur.com/Jvh1OQm.jpg","#","#"];
	imgEL.src[0];
	arr.push(changeImage());
  return arr.shift();
}
 ```
:::
- Play with the Show This Button button.
  - What is the value of the property `onclick` of the button?
 :::info
**Answer:**
* The value of the "onclick" can be the value of the function, which in this case is "event," because the "onclick" equals the function "showButtonData(event)". The "clicking button" itself is the event that is targeted, and it occurs inside of this method.
 :::


### Part 4 - Challenge

- Play with the interface (each of the form inputs) and observe how the program reacts. 
:::info
- For the drop-down menu (INPUT), the initial state (NULL or BASE) is "select your preference"
- Once a choice is selected as an input, the initial state is changed to that particular state (choice options: Americano, Cafe Au Lait, Cuppacino)
- The choice selcted remains until the RESET button is clicked. Then the drop-down menu (INPUT) is cleared out and the final state becomes the initial state (NULL or BASE)
- Once the SAVE button is clicked, you can overwrite your choices by selection some other input forms and clicking the button to update your choices

:::
- Carefully take note of what actions cause what results, in what order. **ALSO**, open up your Chrome Devtools and watch your inspect elements tool pane as you interact with this form.
  - Explain how this program works with regard to STATE, SEQUENCE, and CAUSALITY of each line, and/or specific parts of a line as appropriate. Use specific vocabulary, as demonstrated in the notes section.
:::info
STATE
- Initial: prior to providing input and when the RESET button is clicked, the entire form defaults to this base case. This is consistent with all input select`, `checkbox`, `radio`, or `textarea` forms
- Intermediate: this state has a combination of states for the input forms. Some of the input forms may still not be initialized, while others are in their final state. This is the EVENT when a user is providing the requested input
- Final: this state occurs after the SAVE button has been activated. The information is stored and can only be overwritten with another SAVE event.

SEQUENCE
- define: variables and constants are given values if there are no pre-defined arguments.
- check: the program then verifies if an event, action, state, or boolen value had been determined or defined
- perform: an action is then performed based on the previous steps

CAUSALITY
- functions: used in the JavaScript to create a list of commands or instructions that must be performed. The outcomes are then the end result or outcome for each action
- console/DOM: stores, displays, logs, or toggles the Javascript instructions as specified. It has all level of STATE stored for retrieval. It logs all steps of SEQUENCE for further action
:::

- Be sure to articulate both aspects of the HTML and JS.
  - Explain the differences between `select`, `checkbox`, `radio`, `textarea` with regard to how we get the input `values`.
::: info
`select`: allows one input to be selected at a time unless otherwise specified. There is an option to select multiple inputs if the Javascript and Html code is written to reflect this. The input VALUES are queried in the console using Javascript:
- NULL/BASE case (initializes to this state when RESET button is clicked) results: EMPTY string.
```javascript=
document.querySelector("#coffee").value
''
```
- NON-EMPTY string when input options are selected (one at a time) and the avascript runs to update the final state for the results:
```javascript=
document.querySelector("#coffee").value
'americano'
```
```javascript=
document.querySelector("#coffee").value
'cafeaulait'
```
```javascript=
document.querySelector("#coffee").value
'cappuccino'
```
:::
::: info
`checkbox`: allows multiple inputs at a time unless otherwise specified. The input values are preset in this case and there are stored into an array-like (NODE list) structure. The Javascript function to check/uncheck pushes the preset value to the console based on which checkbox is ticked/unticked.
- PRESET values (checkbox is unticked) results: 
```javascript=
document.querySelectorAll('input[type="checkbox"]')[0].value
'morning'
document.querySelectorAll('input[type="checkbox"]')[1].value
'afternoon'
document.querySelectorAll('input[type="checkbox"]')[2].value
'evening'
```
:::
::: info
`radio`: The default select button is coffee. Each button has a PRESET value that is pushed once the button is clicked.The input values are preset in this case and there are stored into an array-like (NODE list) structure. 
```javascript=
document.getElementsByName("whichDrink")
NodeList(2) [input, input]0: input1: inputlength: 2[[Prototype]]: NodeList

document.getElementsByName("whichDrink")[1].value
'tea'
document.getElementsByName("whichDrink")[0].value
'coffee'
```
:::
::: info
`textarea` : This accepts text in the input and updates it from an inital state of an EMPTY string to the final state of the full text string. The Javascript is used to check for EDITING events as the current state, which is not yet stored. The BASE case is updated to the current state immediately text is typed. The final state is the SAVED state. As editing occurs, an EDITING button is displayed with a caution background to notify the event occurence. The button updates to a SAVED button with a success background color from Bootstrap once the final state is acheived.
- NULL/BASE case (without any text input) results: EMPTY string.
```javascript=
document.querySelector("#why").value
''
```
- NON-EMPTY string when the textarea is updated to a current event state of EDITING:
```javascript=
document.querySelector("#why").value
'Hello'
```
- NON-EMPTY string when the textarea is updated to a final event state of SAVED:
```javascript=
document.querySelector("#why").value
'Hello world'
```
:::
  - What is the importance of the `name` attribute, especially for radio buttons?
::: info
The `name` attribute allows for the creation of radio-groups. This is similar to selecting a particular class except that once a button in the group is selected, the other buttons are automatically deselected.
:::
  - Explain the significance of `e`, `banana`, `bananaEvent`, and `event`.
    - How are they the same and how are they different?
::: info
**Similarity:** `e`, `banana`, `bananaEvent`, and `event` are all INPUT variables or parameters to each of the specified functions
**Differences:** `e`, `banana` are ARGUMENTS which are passed to and received by the function.
`bananaEvent`, and `event` are PARAMETERS to each of the specified functions
:::
- Try tinkering with some of these functions to produce some diffent looking, behaving results in the results pane.
  - Explain what you tinkered with and what the results were.
:::info

- We explored the thought process of what is the minimal set of inputs to have a "saved content" outcome once the SAVE button is clicked: it seems that provided a text input is the only way to achieve this. Any combinations of the other input forms minus the text input was unsuccessful.

- Inital state (NULL/BASE case) for RESULTS section is "No Content"
    - a selection of any of the input (SELECT, CHECKBOX, RADIO) choices produces a button with a specified background color
    - the coffee radio button is selcted as a default, so clicking SAVE without choosing other inputs will consistently produce a COFFEE choice in the results section
- Final states happen when the SAVE button is clicked. The results section displays the badges to confirm the input selection. If the the `textarea` has input, then the final text is displayed in addition to the SAVED badge. 
- Except for the checkbox input controls, the CAUSALITY outcomes for all the other badges are updated to the text and background color to the SAME button. ONE button gets updates for all STATES, EVENTS, and SEQUENCES.
- For the checkbox controls, each SELECTION enables the creation of a new badge. Thus, we have n badges for the n checkboxes if selected (n=1,2,3).

:::

---

# NOTES

I wasn't sure whether to include this supplementary reading as part of the Tinker or a separate document. But here it is. You can read it first, but it probably would help to at least scan through the Tinker questions so as you read this, you can think of the Tinker questions as a context and how they relate, to make sense of some of these extras I've included.

## Programming Overview

You've already "coded" things. HTML/CSS is a way to code web-documents for consuming in browsers, and style documents for declaring how style rules apply to your web-documents. You've learned that there is structure to code, hierarchy and sequence to code, syntax to code, that specific important keywords mean something in code. Now, we're going to go further and start to "program" things using these principles, and then some.

Programming is just a set of instructions (through code) to tell the computer how to execute a particular task, a series of **routines**. There is syntax involved (as defined by the Javascript language) and logic involved (how things should happen, when). This is what really makes the web so powerful - with programming, we can make things react to users, produce human-computer interactions, hopefully in joyful ways.

### How to think about programming

I've been thinking about this one a lot. And from my years of experience, I've kind of distilled it down to three things you should be thinking about with every little thing you learn about programming. Really, these are the golden questions you should ask anytime you are writing, reading, studying programs. That is:

1. What is the STATE of the program?
2. What is the SEQUENCE of the program?
3. What is the CAUSALITY of the things in the program?

That's really it. If you do the following things, pretty much you can start to break problems down into manageable parts, as well as ask the right questions when it comes to figuring out parts you don't understand.

### STATE

> the particular condition that something is in at a specific time

You can imagine that when you visit Facebook for the first time, the program is at a certain zero state. You see a splash page and some marketing to get you to sign up. This state is easy to imagine as you can visually think of the state of the program.

But what you are now trying to see as a programmer, is how the state might be defined beyond the surface of what you can see. For example, we might represent this state as the result of some code like this:

```javascript=
var loggedIn = cookie.authentication;

if (loggedIn === true) {
  showUserFeed();
} else {
  showSplashPage();
}
```

Since we're on the splash page, you can imagine that the state of the program, more specifically, the state of the variable `loggedIn` is false. If they were already logged in, you could imagine the state of the program starting with `loggedIn === true` and therefore, pushing the displayed state to the _user feed_.

Let's say that the user doesn't have an account. We could say that the state of the program is that `var user = undefined;`

Let's say the user starts filling out the signup form and each time they fill in one item, we update the state of the user:

- `user.firstName = "Santa";` State of user (firstName) updated.
- `user.lastName = "Claus";` State of user (lastName) updated.

Each time this user data is updated, we are changing the state of the program. And through these states and assignments of states we can push how the program looks and behaves. For example, if the user leaves the page and comes back, maybe we want the program state not to start back at zero, but to start where the user left off.

States are represented by variables. You set variables to save the state of a particular program. This data that represents a certain state of a program can then be used to do something about it. That is, to _cause_ an update in the way the page looks or behaves as demonstrated in the above example.

**So the takeaway**: When you are learning this stuff, each line, each routine, each little part of a routine, you should be asking yourself:

> What is the state of the variables?
> What is the state of the program?

### SEQUENCE

> a particular order in which related events, movements, or things follow each other.

We've already established how sequence can have an effect on HTML/CSS. As a matter of fact, in Javascript sequence also has an important role. In general, code runs from top to bottom, left to right. However, with programming we have the ability to make for much more sophisticated, and dynamic sequences of things to happen.

```javascript=
var userTopicPrefs = [];

if (userTopicPrefs.length > 0) {
  showPinboard(userTopicPrefs);
} else {
  showTopicPicker();
}
```

In the above code, based on the user's topic preferences we influenced the sequence of routines to happen. Since the user has no preferences (an empty array) we bypased the routine to show the pinterest like pinboard via `showPinboard()` and instead went to a "pick your topic preferences" interaction via `showTopicPicker()`.

Take a look at the following code:

```htmlmixed=
<input type="text" onchange="updateComment(event)" />
<button onclick="postComment()">SAVE</button>
```
```javascript=
var comment = undefined;

function updateComment(event) {
  var inputElement = event.target;
  comment = inputElement.value;
}

function postComment() {
  // get comment data and save it to the database
}
```

In this example, when the text input changes value (user fills it in) the `updateComment` function is called `updateComment()`. This sets the state of the comment variable to whatever text the user wrote in the input.

The `postComment` function is called `postcomment()` when the html button is clicked. And we could get the state of the `comment` variable and send that data to the database.

We could say that the intended sequence of this is:

1. User types in text
  - change event triggered
  - `updateComment()` called with `event` data passed in as argument
    - `updateComment` routine begins
      - `inputElement` is set to the HTML input element, via `event` property of `target`
      - `comment` is set to the text, via the `value` property of `inputElement`
    - `updateComment` routine ends
2. User clicks on the button
  - click event triggered
  - `postComment()` function is called
    - `postComment` routine begins
      - `comment` state is the user text and sent to the database
    - `postComment` routine ends

However, what if the user clicks on the **SAVE** button before they enter any text in the input?

Sequence is more than just the order in which you write your code. When a function is called will change the sequence of what routines, and sub-routines execute. When you have user interactive things (like button clicks) the sequence can change depending on when a user triggers an interactive event. Sometimes, some code might not happen at all. These are all things you need to think about very explicitly and conscientiously.

> What are the independent groups of code sequences (routines) in my program?
> How will the STATES and EVENTS affect the SEQUENCE of the program?


### CAUSALITY

You can't really mention programming without addressing causality. And in our prior work, we've been very adamant about seeing and understanding the causality of things we do. It may seem obvious, but we program things in order to cause things to happen. Mostly, it's about causing:

- Changes to the STATE of the program
- Changes to the SEQUENCE of the program

To be honest, I can't think of anything else any line of code would do. Even things like using code to GET the state of a program, is usually for the purpose of eventually changing the state of the program.

This third golden principle of programming ties the two other golden principles together. Programming is by nature, a very explicit exercise. Understanding how each part of a program, from the higher level logic to the lower level syntax, _causes_ the program to work in a certain way is the key. Each rule in programming usually is tied to a SINGULAR result. Programming has very little ambiguity in that regard. You tell the computer precisely what you need it to do in a very exact way, or it won't work. Ambiguity, is for the humans.

> What does this program routine cause?
> What does this part of the routine cause?
> What does this syntax: symbol, operation, pattern cause? (low-level)

Ask yourself questions regarding these three golden rules with each line of code you write and you should be on your way to understanding it in a more systematic manner.


## FUNCTIONS: Inputs and Outputs

Arguably, the biggest problems I see when students are learning functions are the conceptual understandings around the following things:

- Understanding a `function` _declaration_ vs. a `function` _call_.
- Understanding `function` sub-routines in the context of a larger sequence.
- Understanding the difference between _parameters_ and _arguments_ in relation to INPUTS.
- Understanding the `return` keyword in relation to OUTPUTS.

### Declaring and Calling Functions

> Declaring a function is telling the computer: "Remember this code and run it when I tell you to in the future."

> Calling a function is telling the computer: "Remember that code? Run it now."


#### Declaring

To setup a function, you have to declare a function. That's about it. There is one key giveaway that something is a function declaration.  That giveaway is the keyword `function`. Also note, that when we declare a function we also define it as a block of code to run. The giveaway here is the opening and closing curly-braces `{}`.

```javascript
// Function declaration and definition PATTERN

function funcName(params) {
  // sub-routine defined
}
```

```javascript
function doSomething() { ... }
```
Do you see the keyword `function` above? Yep, it's a declaration. Won't execute on its own but you essentially told the computer to be ready for the future.

```javascript
var doIt = function() { ... };
```
Do you see the keyword `function` above? Yep, it's a declaration. Won't execute on its own but you essentially told the computer to be ready for the future. This function doesn't have a name like the first example (i.e. `doSomething`). It has a reference to it, via the variable `doIt`. But it is nameless. We call this an `anonymous` function. The variable `doIt` becomes the _inferred name_. For the most part, you can treat these similarly although there are some caveats which we might discuss later.

How about this one?
```javascript
doIt();
```
Nope. There is no `function` keyword. Here we are not declaring a function. We can assume it was already declared prior, or maybe declared as a default with the browser, which comes with a set of functions already declared and usable for us.

Let's look at a stranger example:

```javascript
setInterval(function() {
  // code
}, 1000);
```
Do you see the keyword `function` above? Kind of?

Here there are actually two functions. The first is a function named `setInterval`, the second is an anonymous function that we happen to declare right there. Having trouble seeing these two? Let's separate them a little bit so you can see.

```javascript
setInterval( ___ , 1000);

function() {
  // code
}
```

`setInterval` is a function given to us by default. It has already been declared somewhere by our browser. Notice there is no `function` keyword associated with it. Here we are actually _calling_ the function.

The second function is anonymous. There is no name given to it. But it is a `function` and it is being declared right there inside the _call_. Again, the key point is to see the keyword `function` and know that you are declaring a function, and that you have defined a function.

What does this do? `setInterval` is basically a timer. It accepts two parameters. The first argument must be a `function` and second is a `Number`. Basically, `setInterval` needs a `function` that will be used every X milliseconds. Thus, in this example the `function` will run every 1 second interval. Every second, internally, `setInterval` will _call_ the function you passed in. Thus, it is convenient for us to declare a function right within the `setInterval` call, giving us this funny looking but common format. We could have easily rewritten this like the following:

```javascript
function moveClockSecHand() {
  // code to move the second hand of the analog clock
}
setInterval(moveClockSecHand, 1000);
```
It's the same as above, except we declared a named function on the lines prior, and passed that function into the `setInterval` as an argument through the reference.

#### Calling

To use a function, you have to _call_ a function. There is one key giveaway that something is a function _call_.  That giveaway is that you see parentheses `()` immediately after some reference and there is no keyword `function`. The pattern to call a function is the following:

```javascript
funcName();                // Without arguments

funcRef(argA, argB, ...);  // With arguments
```

If you see `something()` or `something(arg, arg)` or something like that you are _calling_ an already declared function. You might have declared it yourself, it might come from the default, it might come from a library like Bootstrap.

You'll also notice that we don't have curly-braces `{}` when calling a function. Makes sense since curly-braces are for blocking off and defining the code to be run. Since we've already done that, when you call a function you won't see any `{}`.


```javascript
doSomething();
```
Do you see the keyword `function` above? Any `{}`? No. So it's not a declaration. Does it fit the pattern of `something()`? With `()` right after the function name? Yup. Thus, here we are _calling_ the function, telling the computer to execute it as it was declared and defined earlier.

```javascript
doSomething("Thomas");
```
Does it fit the pattern of a function call? Yes. Do you see a `function` keyword or `{}`? No. Here, we are _calling_ the `doSomething` function and passing in the argument `"Thomas"` which, depending on how the function was declared - will probably do something with the input.

```javascript
doSomething;
```
Do you see the keyword `function` above? No. So it's not a declaration. Do you see any `()` following this reference in the pattern of `something()`? No. So we are not _calling_ a function either.

Here, this is essentially a variable. Much earlier in this section, we did declare it and define it. So we can say that the variable `doSomething` just points to a function. `doSomething` is a function. But the declaration happened way earlier, and it is not being called right now.

### Thinking of Function Sequence as Sub-routines

A function is basically a block of code, a sub-routine that will execute when you _call_ upon it to do so. Take a look at the following routine.

```javascript=
function setName(someName) {
  myName = someName;
}

var myName = "Anonymous";

setName("George Washington");
myName = "Valentina Tereshkova";
setName("Mark Twain");
```

You can think of the sequence of this routine as executing top to bottom. But keep in mind that the code inside the function `setName` is a sub-routine of the larger code. That sub-routine does not actually happen until the function is called upon `setName(...)`. So the order of how this code happens is the following:

```
Line 1 - function is declared.
Line 5 - variable is declared and assigned a value.
Line 7 - function is called.
Line 2 - sub-routine executes.
Line 8 - variable is assigned a value.
Line 9 - function is called.
Line 2 - sub-routine executes.
```

### Paramters vs. Arguments as INPUT

> A parameter is a variable in a function definition.

> An argument is the data you pass into the function's parameters, when a function is called.

Here is the pattern to understand this:

```javascript=
var kelvin;

function celciusToKelvin(celcius) {
  kelvin = celcius + 273.15;
}

celciusToKelvin(0); // kelvin = 273.15
```

We declared and defined the `celciusToKelvin` function on line 3. Inside the `()`, `celcius` is the parameter, a variable name we made up.

`0` is the argument we pass into the function when we call it on line 7.

We could have defined the parameter like this:

```javascript
function celciusToKelvin(c) {
  kelvin = c + 273.15;
}

celciusToKelvin(-273.15); // kelvin = 0

// OR this in honor of Hawaii's official State Fish

function celciusToKelvin(humuHumuNukuNukuApuaA) {
  kelvin = humuHumuNukuNukuApuaA + 273.15;
}

celciusToKelvin(100); // kelvin = 373.15
```

The computer doesn't care how we define our parameters when we declare and define our function. These variations are essentially the same as the original. What is important is that we give the parameters, variable names that makes sense; because as you can see, it is how we access the data that is passed into the function for use internally by the function.

What people tend to mess up most is that they see an example with a parameter defined a certain way. Then they think that parameter name is something special like a keyword. You might call it `celcius`, I might call it `c`. Strange people might name it after a fish. A common example that messes people up:

Finally, you can pass data in as arguments by reference of course.

```javascript
var myApartmentTemp = 20;
var someTemp = myApartmentTemp;
var x = someTemp;

celciusToKelvin(x); // kelvin = 293.15
```

### Return as function OUTPUT

> Get data back, where the function was called.

Sometimes functions have OUTPUTS. What people confuse is output in terms of data vs. output in terms of behaviors.

For example:

```javascript=
function hello() {
  document.write("Hello");
}
```

Many people have the misconception that the output here is `"Hello"`. This may make sense from a user perspective, it is not what we mean by output from a programming perspective. For example, using the above code if I did something like the following:

```javascript=+
var message = hello() + " World!"; // "undefined World!"
```
`message` would _not_ be set to `"Hello World"`.

Our `hello` function never had any data output. It probably sent data to the screen and printed "Hello" on the page somewhere. But it didn't have a functional data output.

The key point here is when we talk about functions and output, we are really talking about using the keyword `return`.

> Return data back to where the function was called.

For example:
```javascript=
var first = "Jean Luc";
var last = "Picard";

function makeFullName(first, last) {
  return last + ", " + first;
};

var username = makeFullName(first, last); // Picard, Jean Luc
```
`makeFullName` formats the name and returns a string "Picard, Jean Luc" to where it was originally called. That is, the right side of `=` operator. `username` is set to this value.


Or another:

```javascript=
function hello() {
  return "Hello";
}

var message = hello() + " World!"; // "Hello World!"
```

Our function `hello` _returns_ data back to where it was called. The way to think about the above example, line 5 is like this.
```
Right side looks like:

  hello() + " World!"

Evaluate the right side:
  Evaluate the function call, hello()
    returns a string "Hello"
Right side now looks like:

  "Hello" + " World!"

Continue evaluating right side:
  Concatenate "Hello" + " World!"
Right side now looks like:

  "Hello World!"

Assign the variable message to "Hello World!"
```

Take a look at this example:

```javascript=
function halfLife(materialVolume) {
  return materialVolume / 2;
}

var volume = 100;

halfLife(halfLife(halfLife(volume))); // 12.5
```
Since the function `halfLife` will always return a number, we can call it and use the return output number as the argument for the next call. On line 7, we do this 3 times to get 12.5.

As a rule of thumb, if you want your function to have an output, so that you can use that output to construct more sophisticated statements, use the keyword `return` and be aware of what kind of data you are returning.


## HTML and Javascript

There are a few key concepts that I want you to understand for this Tinker, with regard to how HTML and Javascript relate.

The point of Javascript, is to "connect" with HTML. That is, we basically use Javascript to manipulate our things on our HTML page. As we have learned:

- HTML is a language that represents the structure and organization of a web-based, browser readable `document`.
- It consists of things like `elements` and `text` nodes that are structured in a parent-child hierarchy.
- These things have `attributes` and `values` that further shape how these things are represented.

```htmlmixed=
<!-- Within larger HTML Document -->

<div id="kittens" class="cute meow">
  <img src="images/meowth.jpg" />
  <img src="images/purrrr.jpg" />
  <p>
    I really like <span>fluffy</span> kittens.
  </p>
</div>

<!-- Pattern of HTML Nodes -->
<element attrA="valueA" attrB="valueB">
  <element attrC="valueC"/>
  <element attrD="valueD"/>
  <element>
    Text Node <element>text</element> text.
  </element>
</element>
```

Javascript can **_read/access_** the page by `selecting` elements:
```javascript=
var kittenDiv = document.querySelector('#kittens');   // An element: div#kittens
var imageElements = document.querySelectorAll('img'); // List of elements: [imgA, imgB]
```

Javascript can **_read/access_** `properties` of elements:
```javascript=
document.querySelector('#kittens').id;   // "kittens"

document.querySelectorAll('img')[0].src; // "images/meowth.jpg"
document.querySelectorAll('img')[1].src; // "images/purrrr.jpg"
```

Javascript can **_read/access_** other useful properties of elements:
```javascript=
// I'm use "el" as shorthand for "element", a common convention.
var el = document.querySelector('p');
var myText = el.textContent;  // "I really like fluffy kittens."
var myHTML = el.innerHTML;  // "I really like <span>fluffy</span> kittens."
```

Javascript can **_traverse_** the document structure:
```javascript=
var imgOne = document.querySelectorAll('img')[0]; // <img src="images/meowth.jpg" />
var imgTwo = imgEl.nextElementSibling;            // <img src="images/purrrr.jpg" />

var spanEl = document.querySelector('span');      // <span>fluffy</span>
var pEl = spanEl.parentElement;                   // <p>I really like <span>fluffy</span> kittens.</p>
```

Javascript can **_manipulate_** elements:
```javascript=
var imgOne = document.querySelectorAll('img')[0].src; // "images/meowth.jpg"
    imgOne.src = "images/nyancat.jpg";                // "images/nyancat.jpg"

var kittenEl = document.querySelector('#kittens');
var kittenClasses = kittenEl.className;               // "cute meow"
var kittenClassList = kittenEl.classList;             // ["cute", "meow"]
    kittenClassList.add("hungry");                    // ["cute", "meow", "hungry"]
    kittenClassList.remove("cute");                   // ["meow", "hungry"]
    kittenClasses = "dogWasHere";                     // className "dogWasHere", classList ["dogWasHere"]
```

And when you do these things, your page will dynamically change.

### Javascript Events

Javascript, also makes it possible to react to user actions. Common actions are things like:
- Clicking the mouse
- Pressing a key
- Scrolling a mouse wheel
- Pinching on mobile
- Value changes on forms

These things are called **_events_** and there is pattern to how you go about hooking up your JS to these things. That pattern is you need to:

- **_Listen_** for a specific event
- **_Trigger_** an event (often by the user actions)
- **_Handle_** what to do when the event is triggered

There are a few ways to get your page to listen for events but the one we're using for now is to use HTML markup to tell the page what to listen to.

```htmlmixed=
<div onclick=""></div>
<textarea onkeypress=""></textarea>
<input onchange=""/>
```

This `on` `event`, rather `onevent` pattern works for many different kinds of events. What we are doing here is setting a _listener_ for that particular event on that particular element. `div` will do something when it is _clicked_. `textarea` will do something when _key is pressed_. `input` will do something when the `value` changes.

Thus, the `event` part of it is _triggered_ by the user actions.

Finally, what then happens? We need to _handle_ these events. That is, when an _event_ occurs, we need to tell it what function to call. That function is referred to as a _handler_ function. In the above example, you'll notice that the values are all empty. This is where we will tell HTML what the handler should be.

Declare the `printGreeting` function.
```javascript=
function printGreeting() {
  // sub-routine to print greeting
}
```

Attach handler to event. Call `printGreeting()` handler function when click event is triggered.
```htmlmixed=
<div onclick="printGreeting()"></div>
```

This `onclick` attribute and `printGreeting()` value - an event handler call, is the connection between your HTML and JS.

It's worth noting here that when events happen, you might want to know something about the event in your handler function. For example, what kind of event was triggered? What key was pressed? What element was it that triggered the event? (You can have multiple elements share the same handler function).

To deal with this, you can design your handler function to accept a parameter that represents the event data. If you do this, when you call the handler you would pass in an argument representing the event data. For example:

Declare the `printGreeting` function with a parameter to accept event data.
```javascript=
// "e" is an arbitrary name representing the event data
function printGreeting(e) {
  e.target; // element that the event handler was attached to
  e.type;   // "click"

  e.target.innerHTML = "<strong>Hello World!</strong>";
}
```
Attach handler to event. Call `printGreeting(event)` handler function with `event` data passed into function when click event is triggered.
```htmlmixed=
<!-- Call printGreeting and pass in event argument -->
<!-- Here you must use the exact word: event       -->
<div onclick="printGreeting(event)"></div>
```

I want you to study this _pattern_ and recognize where I've used this throughout this Tinker exercise. You should take the process concept: `listen`, `trigger`, `handle` and map it to your understanding of HTML and JS functions. If you can understand this pattern, you'll be able to apply it to all these interesting categories of events [Events](https://developer.mozilla.org/en-US/docs/Web/API/Event). Some of the ones you might find interesting are:
- https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent
- https://developer.mozilla.org/en-US/docs/Web/API/InputEvent
- https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent

Take a look at some of the `properties` available to you through the event argument. For example, `event.type` (I used `e.type` in the example above) is a generic property of all [Events](https://developer.mozilla.org/en-US/docs/Web/API/Event). But if you go into [MouseEvents](https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent) you'll find that there are special properties for mouse events like the click coordinates X and Y. Browse through it and finding linkages between the docs and the examples provided in this exercise.
