---
# System prepended metadata

title: TINKER - Javascript Part II

---


# TINKER - Javascript Part II
- Group member: Yiran, Sandra, and Jiayi 

Codepen: https://codepen.io/jx2517/collab/RwJOqLY
debugger Link: https://codepen.io/jx2517/collab/zYaXMEZ



## Tinker Tasks

In this tinker, were going to:

1. Review prior concepts in this new context:
    - Variables, functions, events, and arrays
2. Observe, analyze, and study new concepts:
    - Control statements (E.g. `if`, `for`)
    - Logical operators (E.g. `===`,`&&`, `||`,`<`,`<=`,`>`,`>=`, etc.)
    - Objects (and `array` of `objects`)
3. Learn how to use more developer tools to study JS code
    - Source (i.e. debugger)
    - Console (i.e. `console.log`, `console.dir`)

We will continue to observe, analyze and think about this program in terms of:

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



### Part 0: Conceptual Program Overview

Play with the program and observe how it reacts to user interactions.

- _Without_ talking about it in _programming terms_ explain the user observable steps/process of the following three interactions and how the program responds.
  - Adding a todo
  - Completing a todo
  - Removing a todo(s)

  Be specific but imagine you are talking to a _non-programmer_. Think about this in terms of observable actions and reactions.
  > User puts toast in the toaster. Sets the length of the timer. Pushes the lever to start the toaster. The toast pops out the toaster after the time is completed and goes "DING".


---

> Adding a todo:
> Write a new todo item in the text box
Add the item with a click of the ADD button

> Completing todo
When todo is completed, click the checkbox of this todo item
Completed todo items will be marked with a horizontal line, 
font color will turn gray and font will be italicized.

> Removing todo
Check the check button of the item you want to delete and click the DELETE button



---

- For each of the interactions above write in _pseudocode_ the steps of how the program for that interaction unfold and results. Pseudocode is semi-formal structure to write out the gist of how your program would work. It uses some keywords but is largely language agnostic. There isn't a single correct way to do it but the following are some rules that can help.
  - RULES:
    - One statement per line
    - CAPITALIZE initial _keywords_
      - READ, WRITE, IF, ELSE, REPEAT, UNTIL, AND, OR
    - Indent to show hierarchy and groups of operation
    - Keep statements language independent

  ```markdown=
  # Making toast for a big family
  READ loaf of bread
  READ slice of loaf
    Put slice in toaster
      WRITE time to toast
      Start the toaster
        Cook the toast
          READ time
          WRITE time by one second less
        REPEAT UNTIL time is zero
    Remove toast
  REPEAT for all slices in loaf

  # Serving toast
  WRITE number of slices total
  READ number of family members
  READ toastiness
  IF toast is burnt AND (total slices >= number of family members)
    throw away toast
    decrement slices total
  ELSE
    serve toast to family member
  ```
- Using your pseudocode, identify the function(s) in the actual JS code that relate to your pseudocode.
  - Compare and contrast your pseudocode with the actual code.
  - Explain what similarities and differences you noticed about the instructions / steps / processes in the code vs. your psuedocode.

> Although it is different from the actual source code writing method, it explains 
the processing flow in a writing method that is close to the source code writing 
method. Unlike source code, it is written in human language, which cannot be 
understood by computers. It can be used as a reference when writing the actual 
source code.


- Manipulate different parts of the code as you see fit. Why did you decide to manipulate that part? What happened? (More structured tinkering to follow.)


>  I tried to add an alert to the `if (todosHTML === "")` process so that when the user complete every items on their todo list, this program will tell them “Good Job!”.


### Part 1: Variables, Functions, Arrays, and Events

- Explain the `data` variable.
  - What does this data (and the data inside) represent conceptually?
> These represent the todo list that has been added. When the browser is refreshed, it will reappear.
  - If I wanted to access the second object, how would I do that in code?
> Use`var secondObj = data[1];`and then call the array index.
  - If I wanted to access the `done` property of the first object, how would I do that?
> Use `data[0].done`

- Look through the rest of the code where this `data` array is used. When the user does things, am I manipulating the visual display and updating the data to reflect those changes? Or am I manipulating the data and updating the visual display to reflect those changes?

> I think the two seem to be happening simultaneously, with the user interacting with the visual interface, which in turn updates the data, and the program simultaneously acting on the data input and updating the visual display.
  - Is this what you would have thought of?

> Yes, it makes sense to me to manipulate existing properties and values to update or create a new visual display.
  - What might be the significance of this program design decision?

> I think it can help us save time updating the visual display if the data changes later.

- What do these lines in my code do?
> These lines declare a variable that is equal to the elements retrieved from the html using `document.querySelector`.

    ```javascript=
    var todosEl = document.querySelector('#todos');
    var inputEl = document.querySelector('input');
    var completedEl = document.querySelector('#counter');
    ```
- Why declare these (see above) variables at the Global scope instead of in the functions?

> So all the functions and code can use them
  - Or not at all... (E.g. `document.querySelector('#todos');`)
> I guess it will make the code shorthand and more easy to read.
- The `toggleComplete` function has an event parameter. Inside the function I access `event.currentTarget`. What is the difference between `event.currentTarget` and `event.target` which we used previously?

> The `event.currentTarget` refers to the element to which the event handler is attached, while `event.target` refers to the element on which the event has occurred.
  - Hint 1: You can add a `console.log(event)` etc. inside that function to test the value of `event.target` and `event.currentTarget`.
  - Hint 2: When testing, click on a todo to "complete" it. Click on two areas: the `li` as well as the `i` (font icon) element to see the differences.
  - Hint 3: You can pass multiple arguments to `console.log()`. I often pass two: first a string label, second the thing I want to log. This will basically make the logs easier to identify if you use `console.log()` a lot.

  ```javascript=
  console.log("SOME LABEL: ", dataToLog);
  ```
>   


- In the `toggleComplete` function, there is a `event.currentTarget.id`. Is that `id` the same thing as the id property in my todo objects in the `data` array?
  - Explain.

> I think they are the same things. The `currentTarget.id` is just like a specification.
- What does `!something` mean? (The exclamation mark) and how is it used in this code when we `toggleComplete`?
> `！` equals to "not". When this function runs, the item will be marked completed on the  list.
- Try calling some of the functions directly from the console. Some will work. Some won't.
  - Explain what you find.
> When I calling function directly in console it shows as undefined, this might because that console doesn't affect the actual code, it just a way for us to check whether  value/properties are passed in properly. 


- Look at the function declarations in the JS panel.
	- _Where_ is each function being called?
> Called by JS

	- _When_ is each function, actually called?
    
> Most of the functions are called through the `if` and `else` statements, but will specifie the state when you call the specific function to run. For example, the function `onEnterKey(event)` is called when adding new todo item and clicking the add button.
	- What parameter(s) does that function have?

> `onEnterKey` use the parameter `event`.


- What is the argument that is passed into the function when it is called?
> For the `validateTask` function, the argument that is passed into the function when it is called the `if(event.code === "Enter")`

- Use the console (in Chrome devtools) to `console.log()` and `console.dir()` the following. What is the difference between `console.log` and `console.dir` and why is `console.dir` kind of more useful for looking at some kinds of data?
    ```javascript=
    console.log(data);
    console.log(todosEl);

    console.dir(data);
    console.dir(todosEl);
    ```
> Depends on different situations, if you want to display the value of a variable on the console, you usually use `console.log()` and properties are displayed in a horizontal orientation. But Using `console.dir()` is convenient because the object's properties are displayed horizontally and vertically, much eaiser to use.

### Part 2: Objects and Arrays of Objects

- Manipulate the different _properties_ of the _objects_ inside the `data` array.
  - Change all todo objects' `done` property to `true`.
  - Change some of the task values.
  - Run your code and explain how this changes what you see and why.

- `console.dir()` the `data` array. Goto the console and _OPEN_ the `> Array(3)` text by clicking on it. Go deeper by opening up the nested objects. Analyze what you see. Then add a new todo through the user interface. `console.dir()` the `data` array again and investigate the insides.
  - What is the difference between `data` before and after adding a new todo?
> After adding a new todo, the data array has a new object with a new id.

- Run the following code:
    ```javascript=
    data.push({
      done: true,
      task: "Goto Aikido Lessons",
      id: getTimeStamp()
    });
    console.dir(data);
    ```
  - What did the code above do?

> Adding new task in todo list.
  - Does our page reflect the changes made? Why or why not? Prove it.

> No. I guess it's because the `updateTodoItems` hasn’t been called. 
  - Does order matter in `Objects`?
> Yes

- What is the difference between `Object` keys (E.g. `done`, `task`, `id`) and `Array` indices (E.g. `0`, `1`, `2`)?

> Object key refer to a data stored using property.
  Array indices refer to a data stored using subscripts.
  - How are they similar?
> They both refer to the data.
  ```javascript=
  var myAry = [123, "Code", true];
  var myObj = {
    id: 123,
    task: "Code",
    done: true
  }
  console.log(myAry[1]);
  console.log(myObj["task"]);
  console.log(myObj.task);
  ```

- Compare the following in the console:
  ```javascript=
  var element = document.querySelector('ul');
  var author = { first: "Mark", last: "Twain" }

  var example = {
    theAnswer: 42,
    student: true,
    hobby: "Fishing",
    sayHello: function(){
      alert("Hello");
    },
    favNums: [1,2,3],
    favAuthor: author
  };

  console.dir(example);
  console.dir(element);
  ```
  - What is an `element` really?
> In this case, `element` is `ul`
  - How does our `element` relate in terms of similarities and differences to `example`?
> They both can contain an object and different properties. But `element` is an array while `example` is an object.
  - If I wanted to call the function in the `example` object, how would I do that? Prove it.
> We're having trouble with this question...

:::success
not sure, possible way: 
For example, we can:
```javascript=
example.sayHello; 
```

:::

- Try the following code in the console. How does dot notation and bracket notation differ and why would you want to use one or the other?
> 
  ```javascript=
  var x = "username";
  var user = {
    username: "happyCat"
  }
  console.log(user.username);
  console.log(user["username"]);
  console.log(user[x]);
  console.log(user.x);
  ```
- Identify various areas where the `.` object notation is used and explain the thing on the left side of the `.` and the thing on the right side of the `.`

> `document.querySelector()`  is used to pull information from the HTML.
  - E.g. `document.querySelector()` `document` is... `querySelector` is...
  - HINT: There are MANY choices here.

- In two areas of my code, I use what is called a `filter` function. It's a function that arrays can use like `list.pop()`, `list.push()`.
  - How does a filter function work?

> It create a new array with all elements of the array that match the conditions.
  - What is the significance of the function argument that is passed INTO the filter parameters?

> It can specify what kind of data, with what kind of attributes, based on the filtered data set you want.
  - With regard to the function that is passed into the filter as an argument, that function must `return` a boolean or evaluate to a boolean. What is the purpose of this?
> Because the filter function takes out only the elements that match the conditions and uses them when creating new arrays.
  - What does the _filter function_ return?

> It will return all array element that are `true` based on the test.
    E.g. `var x = list.filter(...); // What was returned to x?`
    - CAUTION: NOT the function argument that goes into the filter.
    - HINT: If you don't know, can you use console to "test" an idea out?
  - Does filtering an array _change_ the original array?
> No, it will not affect.

### Part 3 Control Structures

- I use the `if` statement in several places in this code. Explain why a conditional is necessary in:
  - `updateTodoItems`
  - `updateRemoveButton`
  - `onEnterKey`
  - `validateTask`
  - `addTodoItem`
  - `getTodoData`
  - HINT: You might want to `console.log` the boolean condition where you see the `if` statements to understand what condition we are evaluating.
  ```javascript=
  if (booleanCondition) {
    ...
  }
  console.log(booleanCondition);
  ```
  - Comment on how the boolean condition works as there are many different examples.

:::success
The boolean functon is helpful in the `if` statement since usually `if` stament only have two different conditions where as `boolean ` also only have two status. Where as `number`, or `string` may not be able to achieve. 

The boolean functions check if an event occurred or a particular condition is true and then evalauates a series of subsequent instructions. It usually evaluates a binary condition and then changes a state of an item (string, number, event, etc.) per the intructions provided.
:::
- In this code, there are two kinds of `for` loops. The more traditional that looks like:

    ```javascript=
    for (var i=0; i < list.length; i++) {
      // CODE
    }
    ```
    and a `for of` loop that looks like:
    ```javascript=
    for (item of list) {
      // CODE
    }
    ```
  - How does a `for of` loop work?
:::success
The `for of` iterates through an array, list, string, etc. and applied the conditions/instructions specified to every object or member of the collection. It goes through the entire collection and then stops when the last item in the collection has been reached.
:::
    - What does the `item` represent? (It can be named anything: `x`, `item`, `thing` etc.)
:::success
In the `for of` loop, it saves lots of code writing. In this example: the item represent the item represents each array in the `list ` object. 
```javascript=
    for (item of list) {
      // CODE
    }
```  
It represents a token or a moniker that points to the members in the collection of objects, strings, numbers, or booleans in a particular list. The syntax `for (xxx in list)` is the standard. Thus, the name can be represented by any combination of strings. The name is just a placeholder in the standard syntax.
:::
  - Why are `for of` loops convenient compared to the traditional `for`?
:::success
This is becuase it saves lots of code writing, and also, it does not need to determine the length of `i`, and whether i is increasing or decreasing, or which is the minimum or maximum `i`. 

The use of the `for of`  reduce the number of steps and processes that the traditional `for` loop requires. Although it may seem like a more elegant solution to coding, it eliminates a couple of touchpoints where errors may occur with coding and also reduces the number of steps required in processing the code. For example:
         `for of`  | `for` 
step 1: eveluate/iterate condition  | define the index or iterator
step 2: N/A | define the constraint
step 3: N/A | eveluate/iterate condition over members in the collection

So `for of` starts the iteration in one step while `for` starts the iteration after 2 steps or processes. We gain efficiency on using `for of` coding
:::
  - For what purpose(s) do I employ a `for` or `for of` loop in this program?
:::success
The purpose of have `for` loop can be varied. Some common one that I observed in the coding is that: 
when I need to updating some arrays' status from one object or add information/adjust certain array based on the event that user clicked. 

Then we can use push function to updated to specific HTML. 

The traditional `for` loop works for the case when you want to use the index of the array in performing certain operations. It is more of a brute-force approach because you want to be intentional about each array index. Note that if you wanted to move in a fashion different from increasing by one, the traditional `for` loop would be the obvious choice. 
:::
  - On Facebook or Pinterest, or Twitter, how does a loop through data relate to the display of content?
 
:::success
They can use `for` loop to refer the data on specific object based on the event that triggered by user. Then, `for` loop can add/modify the condition to change `CSS`, `font`, `html` to achive the display of content itself. 

The "FEED" on these platforms that require replication and appending new data inputs rely on looping the data and then displaying it. 
:::

### Part 3 Specific Routines

- Take a look at the `updateTodoItems`. Comment it out and replace it with this alternate, but functionally identical version. How does this function work and how do they relate / differ?
```javscript=
function updateTodoItems() {
  todosEl.innerHTML = "";

  if (!data.length) {
    var liElement = document.createElement('li');
    liElement.innerText = "Nothing todo...";
    todosEl.appendChild(liElement);
  } else {

    for (todo of data) {
      var liElement = document.createElement('li');
      var iElement = document.createElement('i');

      liElement.id = todo.id;
      liElement.onclick = toggleComplete;

      if (todo.done) {
        liElement.className = "complete";
        iElement.className = "fa fa-check-circle-o";
      } else {
        iElement.className = "fa fa-circle-o";
      }

      liElement.appendChild(iElement);
      liElement.innerText = todo.task;

      todosEl.appendChild(liElement);
    }
  }

  updateRemoveBtn();
}
```
:::success
Both routines produce similar results. There is an update in a similar format as the one in the code. The DIFFERENCE is how things are getting updated: the current code updated using appending items or objects to the data, while the routine above uses element and class properties to updated the collection. 
:::
- Take a look at the helper function `getTimeStamp`. This function will return a number, in milliseconds, the current time stamp since January 1, 1970.
  - I call this when I create new todo items, what are some ideas as to why I might be using a timestamp for todo `ids`?
:::success
Since ID must be unique for each array. Have `getTimeStamp` will be a good option since user enter the `todo item` in a different time slot which is a perfect way of representing as`id`. 
:::
- Take a look at the incomplete functions `markAllComplete` and `updateItemsLeft`.
  - Can you complete these and add the functionality to this app?
:::success
This is the code for `markAllComplete` function: 
```htmlembedded=
<button onclick = "markAllComplete()"> Mark All Complete </button>
```

```javascript=
function markAllComplete() {
  data.forEach(todo => {
    if(todo.done != true)
      return todo.done = true;
  });
  updateRemoveBtn();
  updateTodoItems();
}
```

This is the code for `updateItemLeft` function: 
```htmlembedded=
 <h1 id="itemLeft"></h1>
```

```javascript=
 var itemLeft = 0;
  data.forEach(todo => {
    if(todo.done == false)
      itemLeft ++; 
  });
  
  document.querySelector(`#itemLeft`).innerHTML= `you have ${itemLeft} item(s) left`;
}
```

:::
### Part 4 Debugging, Tools

Using the Chrome debugger (source) tool create breakpoints and watch the program execute line by line, part by part. Experience how this tool can give you insight into your program's _STATE_, _SEQUENCE_, _CAUSALITY_.

#### Chrome Debugger

- Set breakpoints at the following locations of your program
  - `function initializeTodos`
  - `function onEnterKey`
  - `function addTodoItem`
  - `function toggleComplete`

- Use the `Step over the next function call` feature to watch how the program pauses during the _SEQUENCE_ of its routines.
- Use the `Step into the next function call` feature to watch how the program pauses during the _SEQUENCE_ of its routines.
  - What is the difference between `Step over` and `Step into` and how does this help you understand programs?
:::success
 The difference between `step over` and `step into` is that: 
- `step into` will run the code line by line and helps you to understand each line of the code and will jump to other function if it contains other function inside of this function. 
- However, `step over` will analyze the code within that you plan to debug with without jumping to other functions.  
:::
- Use `Step into` until you've reached the line `var inputEl = document.querySelector('input');`. Should be highlighted in blue.
  - Highlight the variable `todosEl` on the line before it and `right click` on it. Select _Evaluate in console_.
    - What does the console print?
 :::success
 When the variable `todoEl` is been highlighted, it has "Evaluate selected text in console" only. And the console will print as the follow: 

![](https://i.imgur.com/bf43QEV.png)

 
 :::

  - Highlight the variable `inputEl` on this highlighted blue line.
    - Why does the console say `inputEl` is undefined?
 :::success
 The `inputEl` is undefined because the input does not assigned with any value yet since user didn't input any value. 
 :::
    - When you step through your code, does the blue line represent code that is about to be executed or code that has already executed? How do you know?
 :::success
The blue line code is represent the code that is about to be executed. As image shows below: the code highlighted in blue usually does not have the current value marked in the end. 

Once you press the `step into`, the code will be executed and will have some notes to the right.Then the next code will highlited in blue. 
![](https://i.imgur.com/as9Jajj.png)

 :::
    - What do you predict would be the console value of the variable `completedEl` on the next line if you _Evaluate to console_ at this point?
    
 :::success
 It will be `completedEl = undefined;`. 
 :::
- Watch how debugger annotates your source code with the updated _state_ of different variables as your program progresses.
  - How does the debugger behave when you enter a loop in your program?
 :::success
 When you enter a loop in a program, you will evaluate the same code repeatedly until you reach the exit condition.
 :::
  - How does the debugger behave when you reach the a `filter` function call?
  :::success
 When reached to `filter` function, it will executed the code and on the most right side will appears the filterred data. 
 :::
  - What does filter do and how does it work?
  :::success
 When apply the `filter`, it will search from an object that you designated for based on the requirement you asked. 
- For example as the picture show below, computer will search from the array from the `data` object when array matched with property as:  `todo.done === true`. 
  - In the end, it will return two match arrays. 
 ![](https://i.imgur.com/SpXNPsq.png)
 
 :::



### Part X: Putting all together

**Explain the program line by line with sufficient details, part by part.**
:::success

>
(In the following portion, we will explain current JS code to understand how "Todo list X" works: https://codepen.io/jx2517/collab/RwJOqLY):
> [color=#130f77]


----- **Step 1:**
* Assign all important (3) global variables.
* Assign data objects and it contains 3 arrays (original todo items).   

----- **Step2:**
* Function UpdateTodoItems():Updated the todo List items also the remove button when user made any changes. 
    - Create a for loop to check whether the todo task is completed or not:  
         - If Todo task is completed: Add it to "Todo List" inner HTML and assigned class="complete" to ensure it has special CSS and color. 
         - If Todo task is incomplete: Add it to "Todo List" inner HTML
         - if there is no Todo task : Add "Nothing todo..." to "Todo List" inner HTML. 
     - In the end, updated the remove button. 

* Function initializeTodo():Update the UpdateTodoItems. 
* function updateRemoveBtn():Update the # completed items from remove button and disable the button when necessary. 
  - Determine # of completed item by filter the data objects. 
    - If there is completed items: updated the # of completed items on remove button by updating the `textContent` property for `completedEl`. 
    - If there is no completed items : disable the remove button. 
* function onEnterKey(): When user hit "enter" to input their todo items, and gets updated to the "To Do List" by running "function addTodoItem()". 
* function validateTask(): If the user accidentally enter blank for the "To Do List", this function will prevent this happenning by creating the `task` status as `false`, others will return `task` as `true`. 
* function addTodoItem(): When user hit "enter" or click "add" button, addTodoItem will be triggered to add new array into data object, and List will gets updated. 
  - When user uses hit "enter" and there is empty string, then function will not add any new array to data. 
  - When user input some todo items: 
    - It will create the new array with properties: ID(number), task(string), and done (boolean)
      - ID is been created by applying function: getTimeStamp.
      - Done is setted as `false` state.
      - The value of the task is based on the "to do" item that the user entered.  

  -  Run the function updateTodoItems() to referesh the todo item list. 
  -  Run the function resetInput(): for the user can continue add the new to do items. 

* function resetInput(): To Empty input string, therefore the user can continue add the new to do items.
* function toggleComplete(): When user click on the radio that on the To Do List, it will change the status of task done status, CSS and font style. 
  - When user click on the specific todoItem on the "To Do List", the ID has been obtained from the data object.
  - Run the getTodoData based on the ID we obtained to determine the array that matched with the ID we have. 
  - In the end, reverse the array's done's status. And updated the todo item list.  

* function getTodoData(): Using for loops to find the array from the `data` object that matched with the specific`id`. 
  - If the id matched with the array, input the array to `todoFound`, else `return null`. 
* function removeTodoItem(): When user clicked on remove button, all completed task will be removed. 
  - Update the data object: using `filter` function to keep all the arrays that contains `todo` status as `false` from the data object. 
  - Then update the TodoItems. 
* function getTimeStamp(): using the function `Date.now()` to create a time stamp.  

:::
**Make it yours (group's)**
:::success
- Try to extend this program to do something cool, as a group, your own original idea(s).
	- What is something that a Todo list or todo list user might benefit from?

There are several ideas: 
1. Recover the deleted todo items. Sometimes the user may regret or accidentally deleted certain item, therefore how to make the deleted item back is important to improve users experience. Or we can create an alert message as "You sure you want to delete this todo item?", if they click "yes" then they can delete it, and "no" as nothing will changed.

2. Try to create a completed item list. Show the user the todo item they completed can improve their user experience also. 

3. Create "Select All" button. Therefor the user does not need to click unchecked item one by one. 

4. Create a way to prioritize todo item. Sometimes the user wants to put the most important item in the front and least in the back to remind them which one will be important. We can try to bold or highlite todo items to help improve the user experience.  
:::
