# Tinker 5: Javascript Part II
**Group member**: Ryan Yong Choi, Lisa Lei, Jinny Park
<!--
- See repository: https://github.com/jmk2142/TodoMSTU5003
- See demonstration: https://codepen.io/jmk2142/pen/oGxwPQ
- Tinker Markdown: https://hackmd.io/zJmA8GKJR5-Oe2Zy4r1wqw?both-->
## Part 1
- Explain the `data` variable.
- What does this data (and the data inside) represent conceptually? **They represent the list of tasks, and each task has an id, task name, and done properties.**
- If I wanted to access the second object, how would I do that in code? **data[1]**
- If I wanted to access the `done` property of the first object, how would I do that? **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?
- Is this what you would have thought of?
- What might be the significance of this program design decision? **[Answer to both questions]: updating data first through todosHTML += `<li id="task-${ todo.id }" class="complete" onclick="toggleComplete(event)">`;
then inside the toggleCompelte function, the "done" property of the given "task" will be set to the opposite of what it is, which is then visually updated on the webpage. It is easier to reflect the data that has already been changed (since the values have been changed and we simply have to output that value onto the webpage), than it is to output a change that needs to be done, then to change the values of the variables.**
- What do these lines in my code do?
```javascript=
var todosEl = document.querySelector('#todos');
var inputEl = document.querySelector('input');
var completedEl = document.querySelector('#counter');
```
**Those lines of code bring in the "todos", user input, and the number of completed elements, respectively, from the HTML file.**
- Why declare these (see above) variables at the Global scope instead of in the functions?
**It is the ensure that the variables can be accessed/used by all functions, since if a variable is declared within the confine of a function, it wouldn't be accessible after the function call comes to an end.**
- Or not at all... (E.g. `document.querySelector('#todos');`)
- 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? **Target specifically focuses on the element that actually triggered the event, whereas currentTarget is the element itself that is attached to the eventlistener**
- 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. **No, the id given by event.currentTarget.id is different from the id property within the array. event.currentTarget.id is referring to the HTML element id itself, whereas the id property is id number that we set in javascript array of task objects.**
- What does `!something` mean? (The exclamation mark) and how is it used in this code when we `toggleComplete`? **something directly means NOT something. If it is a boolean, then !true = false and !false = true.**
- Try calling some of the functions directly from the console. Some will work. Some won't.
- Explain what you find. **most of the functions with event parameters do not work, because we cannot access the events from HTML using the console**
- Look at the function declarations in the JS panel.
- _Where_ is each function being called?
- _When_ is each function, actually called?
- What parameter(s) does that function have?
- What is the argument that is passed into the function when it is called?
**[Answer to all questions]:
-initializeTodos() : start of the app itself
-updateTodoItems() : called in initializeTodos() at the start of initializeTodos()
-updateRemoveBtn() : in updateTodoItems() at the end of the function
-onEnterKey(event) : in HTML when you enter a task
-validateTask(task): at the beginning of addTodoItem()
-addTodoItem() : in onEnterKey(event) when "Enter" happens on the webpage
-toggleComplete(event): updateTodoItems() if todo.done is false
-removeTodoItem(event): in HTML when you click the remove button
-resetInput() : at the end of addTodoItem() given that validateTask() returns false
-getTodoData(id) : in toggleComplete(event) after id is replaced
-getTimeStamp() : in addTodoItem() given that validateTask() returns false
parameters:
-event: onclick/enter
-task: string
-id: number**
- 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);
```
**console.log is more useful for outputting actual javascript elements (variables). When we use log to display the data variable, for instance, we were able to see that the variable was an array of objects, whereas with dir, we could not find much in regards to the variable. However, when we are dealing with HTML elements dir is a lot more useful, in the sense that it displays all the properties of that HTML element. As for using console.log with HTML elements, it simply displays the code itself and nothing more.**
## Part 2
:::info
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.
:::
As shown in the picture below, after changing the object's property to "true" and changed the last item's task value property to "change the hamster's padding", all tasks in the list took on the "completed" css style. And obviously, the text string of the last line of property also changed.

As for the style change, in `function updateTodoItems()`, there is a line of code stating:
```javascript=
if (todo.done)
{todosHTML += `<li id="task-${ todo.id }" class="complete"
onclick="toggleComplete(event)">`;
todosHTML += `<i class="fa fa-check-circle-o"></i>`; // Font-awesome
}
```
which means, if the item's "done" property is true, the item's font and style printed on the webpage will be modified.
In the same function, this other line:
```
todosHTML += `${ todo.task }`;
```
changes the text content of the todo task. Since I modified the `task` class for the last object in the `data` array, when runding this ```todosHTML += `${ todo.task }`;```line, the content of the last item will be modified.
:::info
`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?
:::
As shown below: this is the `console.dir(data)` without adding a new item list.

Broadly speaking, it shows the information of each item in the list (their order in the list, the id number, the task string, "done" value, and the total length of the string). After clicked open each arrow/carrot next to each of the object, more details are shown, including a thing called `[[prototype]]` Before we expanding anything, the value of `[[prototype]]` here is "array", which makes sense, because `data` _is_ an array. This is what's it like after we open the `[[prototype]]:Array(0)`tab:

There are so many little properties under `[[Prototype]]`, each of them seems to be associated with a function. I also clicked open the `assign` property, it describles the length, name, argument, and caller of `assign()`, and the function `assign()` itself has its own `[[Prototype]]`, and within the `[[prototype]]`of the `assign()` function, there's another `[[prototype]]`.
Besides that, I also find a more familiar feature: `hasOwnProperty`.

We learned about this in FCC a few weeks ago(or last week?), this is a **method** that's used to check whether an object has a certain property in it. The method looks like a function here (because of the `f hasOwnProperty()`)I don't really understand why the length of this method is `1`here.
I added one line: "Dinner with Rhea" in the text input box and submitted it. I ran the `console.dir(data)` again, this is what I got:

Obviously, the length of the array increased by one. The "done" property for `Array[3]` (the latest added item) is `false`
:::info
Run the following code:
```javascript=
data.push({
done: true,
task: "Goto Aikido Lessons",
id: getTimeStamp()
});
console.dir(data);
```
* What did the code above do?
:::
Another object is added to the data array. The `task` class of this object is "Goto Aikido Lessons", the value of its `done` class is `true`, and the id value is calculated through the function `getTimeStamp()`, which is defined as this:
```javascript=
function getTimeStamp() {
return Date.now(); // this returns a timestamp in milliseconds since 1970.
}
```
:::info
* Does our page reflect the changes made? Why or why not? Prove it.
:::
No. After the code is enter, the array does change, as shown in the console:

However, the page remains the same. The new todo item isn't added to the page
:::info
* Does order matter in Objects?
:::
We don't think it matters. The 4th object "Goto Aikido Lessons" was successfully added to the array, and obviously its classes are not in the same order as the previous objects. As long as they are there, and the user can call them via `object.class`, they should be valid.
:::info
What is the difference between `Object` keys (E.g. `done`, `task`, `id`) and `Array` indices (E.g. `0`, `1`, `2`)?
- How are they similar?
```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);
```
:::
As the layout of the code above, `myAry[0]` and `myObj.id` would get the same string (technically. string with the same content). However, the `keys` are used to call the class of an object, whereas the `indiced` are used to indicate the item within an array. So, fundamentally, the big container (onject vs. array) are different. Besides, order doesn't really matter for the classes of an object. Just as the example above, we can refer to the class no matter which order it is in via the `object.class` notation. Yet, the order within an array is crucial. The indice refer to a very specific item.
:::info
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?
:::
As shown in this code, the element refers to the specific thing (in this case `document.querySelector('ul')`) it grabbed from the html.
:::info
How does our `element` relate in terms of similarities and differences to `example`?
:::
element has a specific representation on the webpage, whereas example is the object written in javascript, and does not have a visual representation yet. Accordingly, `console.dir(element)` returns specific information (including the `id`, `innerHTML`, style information, `textContent`), yet the `console.dir(example)` returns the information of the javascript code, including each class's info and the functions embedded (found in `[[protocal]]`)
:::info
If I wanted to call the function in the `example` object, how would I do that? Prove it.
:::
Instictively, I'd do `example.sayHello`

I tried that, the function is returned to me, but I didn't see the alert poping up.
Then, I tried `example.sayHello()`, it worked and the alert popped up.

:::info
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);
```
:::
The first three returned the same thing, the string `happyCat`, whereas the last one is "undefined". It seems like dot notation cannot accept a variable as a class it's calling. I have been confused by this since last week, and I looked it up before this assignment (when we were doing the FCC for last week).
According to [this page](https://codeburst.io/javascript-quickie-dot-notation-vs-bracket-notation-333641c0f781), althogh dot and bracket notation can both extract the same content, dot notation cannot be used if the class name is referred in a variable or a name starting with a number.
For instance, it cannot recognize the `user.x`, for x is a variable. If a variable is defined as `var 1username="lisa"`, dot notation won't work either. It has to use bracket notation in these two cases. Besides. in bracket notation, the value in the bracket has to be a string.
:::info
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 `.`
- E.g. `document.querySelector()` `document` is... `querySelector` is...
- HINT: There are MANY choices here.
:::
Those are the 3 areas I've chosen:
1. `todo.id`
- "`todo`" is each of the **object** included in the big array, `data`. `id` is one of the **classes** of the `todo` object.
2. `completedTodos.length`
- `completedTodos` is a **variable** defined as `var completedTodos = data.filter(function(todo){
return todo.done === true;
});` It means all the objects within the data array that has a `done` class's value of `true`, `length` is the **property** of the variable. The whole thing will tell us how many (the length) things on the todo list are completed (the objects within the `data` array with a `done` value of `true`)
3. `document.querySelector('input');`
- I remebmer Jin mentioned in a previous video that the `document ` refers to the **entire html document** for the website. I know the function of `querySelector('input')` is to extract content within the `input` element, but I don't know what it is exactly. I looked it up [here](https://www.javascripttutorial.net/javascript-dom/javascript-queryselector/#:~:text=The%20querySelector()%20is%20a,Code%20language%3A%20JavaScript%20(javascript)):query selector is an element **method**.
:::info
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?
:::
The filter functions are used here:
```javascript=
var completedTodos = data.filter(function(todo){
return todo.done === true
});
```
and here
```javascript=
var incompleteTodos = data.filter(function(todo){
return todo.done === false;
});
```
As I have explained above, they are used to select items with a certain feature. For instance, in this case, they're looking for objects within the data array that has a `done` class's value of `true`(the first one) or with the value `false`.
:::info
What is the significance of the function argument that is passed INTO the filter parameters?
:::
The parameter defines the **context** of the selection. In this case, we are only "filtering" the `todo` objects within the `data` array.
:::info
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?
:::
It means the function will return todo objects that _**has**_ the boolean value. For instance, if the argument is `return todo.done === false;`, it's asking the filter function to return todo objects whose `done` value is `false`. If the object does not return this argument, it will NOT be selected.
:::info
What does the _filter function_ return?
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?
:::
It returns the items that 1) are within the paramater's context 2) return the function's argument. In order to prove this, I created a new variable x. and this is what I did:

I changed the function argument to `todo.task ==="Wake up"`, and as I expected, the only item that is within the context (todo object within the data array) and returns the function argument is the task "Wake up".
After the function is called, I called the `data `array again, and the array still returns the same content.
### 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.
> Updating a conditional is nessary in the following booleanConditions becasue they directly impact the functions of the code. Privious booleanCondition will have direct impact on the following booleanCondition [color=pink]
> - `updateTodoItems``updateRemoveButton``onEnterKey``validateTask` `addTodoItem` `getTodoData`[color=pink]
> I commented out `onEnterKey`. Here is when I commented out the condition of onEnterKey. AS one can see in the console, SyntaxError is caught. It affects the codes below the line as well.[color=pink]
- 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?
- What does the `item` represent? (It can be named anything: `x`, `item`, `thing` etc.)
> From my understanding `for of` works as simplied version of the for loops. Thus, both are used in repeating certain code for a selected number of times[color=pink]
- Why are `for of` loops convenient compared to the traditional `for`?
>`for of` loops is more convinient as it does not require to enter the rules of the arrays. It's rather in the simpler form as itto select certain item of the list instead of writing out a rule.[color=pink]
- For what purpose(s) do I employ a `for` or `for of` loop in this program?
> In this particular case, Dr. Kuwata employed `for` loop isntead of `for of` since it requires more specified rules for the wide range of possible answers that may be entered by the users, thus the Loops work image accordingly.[color=pink]
- On Facebook or Pinterest, or Twitter, how does a loop through data relate to the display of content?
>On Facebook or Pinterest, or Twitter, a loop through data, the loggin in system works smilar to the TO List. Yet as all three platforms are image based [color=pink]
### 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?
>Once I comment out `updateTodoItems`,The lists under the todo list under TODO LIST X is no longer there. Also even though I Add new line, it will not reflect. [color=pink]
>
>Before commenting out `updateTodoItems`
>[color=pink]
>After commenting out`updateTodoItems` 
[color=pink]
```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();
}
```
> After applying this code and replacing with the filler data, it remained the same as commenting out.Rather gave me the message below: [color=pink]

- 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`?
> We think you might be using a timestamps for todo `ids` because it allows to get the current time stamp.Some other `ids` that can replace `getTimeStamp` could be `localDataTime` but it will not reflect the time specific when its entered. [color=pink]
- Take a look at the incomplete functions `markAllComplete` and `updateItemsLeft`.
- Can you complete these and add the functionality to this app?
We added a "Mark All Complete" button and wrote a `function markAllComplete()` for it.Following is the code, and we explained each step's corresponding purposes:
```htmlembedded=
<!--this is under the div class="control"-->
<button onclick='markAllComplete()'> Mark All Complete </button>
```
```javascript=
function markAllComplete() {
for(todo of data){
todo.done=true; // Changes all todo objects in data as done:true
}
updateTodoItems();
// we borrowed the existing updataTodoItemsa() function and the updateRemoveBtn() , so that after this function is called, other features will change acchordingly
```
## Part 4
:::info
- 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?
- 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?
:::
1. Soon after pressing the `Step over the next function call` , the screen immediately changed to the iamge below. This is different from what we had seen from Jin's Demo video. We think what it did is that is skipped to the next function. Because the next function requres var
 `var Appcues`, that's why the sentence starts with `var` not function
2. While `Step over the next function call` steps OVER to the next function, `Step into the next function call`allows look into the particular function. From our understadning, the main difference between `Step over` and `Step into` is that first one is stepping over to the next function and step into is stepping into the function told. Thus, both are used in different situations: `Step over` is used when want to step over a step and jump into the next one whereas `Step into` is used to look into the particular function - To go to the next line.
3. Maybe there's something wwrong with my code, on my screen, I cannot use any of the `Step over` and `Step into` for me to get `var inputEl = document.querySelector('input');`. This is what I am getting:
:::info
Highlight the variable `inputEl` on this highlighted blue line.
* Why does the console say `inputEl` is undefined?
* 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?
* 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?
:::
1. the `inputEl` is undefined because there's nothing in the list yet.
2. the blue line represent the code that is **not yet executed**. Because when the line is in blue highlight, when I hovered the mouse over certain properties of the line, the value of the line is still not updated

As the picture has shown, it was already my 3rd time clicking, so supposingly, it should be processing the third object, which is "change hamster's padding" in this case. However, when I hover over the `todo`, the value of `todo` is still shown as "Eat breakfast". That means the code hasn't been executed yet for the 3rd item of the data array.
3. I predict it's probably undefined, for `completedEl` is associated with the `Remove` button, which hasn't been used yet.
:::info
- 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?
:::
- **it shows all iterations and the states of each variable inside the loop until the loop terminates**
:::info
- How does the debugger behave when you reach the a `filter` function call? (answer below)
- What does filter do and how does it work?
:::
**(for both questions) it creates a new array and it'll contain whatever elements from the old array that passed whatever test was provided for the function**
## Part X
:::success
Explain the program line by line with sufficient details, part by part.
* Line by line
* Part by part
* Be sure to copy blocks of code into this markdown using code formatting/fences as references to your explanations.
* For repetitive code, you can explain how a line works then summarize how it would work for the rest.
:::
We will start by explaining the html portion.
Looking on the outside, the "Todo List" program has a heading ("Todo List"),
```htmlembedded=
<h1>TODO List X</h1>
```
a body of checklist,
```htmlembedded=
<ul id="todos">
<!-- ITEMS HERE -->
</ul>
```
an input box, an "add" button and a "# Remove" button.
```htmlembedded=
<div class="controls">
<input type="text" onkeypress="onEnterKey(event)">
<button onclick="addTodoItem()">Add</button>
<button onclick="removeTodoItem()"><span id="counter"></span> Remove</button>
</div>
```
At the end of the page, there is a link to allow it switch to a simpler version.
```htmlembedded=
<a href="https://codepen.io/jmk2142/pen/LzNLqM" target="_blank">Simple Version</a>
```
According to the html, there are already a few places associated with the JS code, such as the `function onEnterKey(event)`,`function "removeTodoItem()`, and `function addTodoItem()`
Looking into the JS code, the first variable is the `data` array.
```javascript=
var data = [
{
id: 1497141891479,
task: "Wake up",
done: true
},
{
id: 1497141913701,
task: "Eat breakfast",
done: true
},
{
id: 1497141937545,
task: "change hamster's padding",
done: false
}
];
```
This array corresponds to the `<ul id='todo'>` in html, and when the `task` changed, the displayed text content on the checklist changed; when the `done` value is true, there is a horizontal line sweeping across the content. When it's `false`, there's no line cross, and the font also changes. the corresponding display of the `data` array is shown below:

We then have a few html element stored as JS variables:
```javascript=
var todosEl = document.querySelector('#todos');
var inputEl = document.querySelector('input');
var completedEl = document.querySelector('#counter');
```
`todoEl` correspond to the content of `<ul id='todo'>`, `inputEl` corresponds to
`<input type="text" onkeypress="onEnterKey(event)">`
and `completedEL` corresponds to the remove button `<button onclick="removeTodoItem()"><span id="counter">`
the following:
```javascript=
function initializeTodos() {
updateTodoItems();
}
```
calls the `updateTodoItems` function, which is specified how the items in the array `data` should be displayed in the list.
Since the function is pretty long, we will explain how the `updateTodoItems` function work via commentting the original function:
```javascript=
function updateTodoItems() {
var todosHTML = ""; //creates an empty string variable
for (todo of data) { //iterate through data array, in which todo is the iterator
if (todo.done) { //if done === true
todosHTML += `<li id="task-${ todo.id }" class="complete" onclick="toggleComplete(event)">`; //concatenate the empty string with the id of the todo task
todosHTML += `<i class="fa fa-check-circle-o"></i>`; // Font-awesome //put a check mark in the circle
} else { //if done != true
todosHTML += `<li id="task-${ todo.id }" onclick="toggleComplete(event)">`; //empty out the check circle
todosHTML += `<i class="fa fa-circle-o"></i>`; // Font-awesome
}
todosHTML += `${ todo.task }`; //add the task to the string
todosHTML += `</li>`; //to close list item in html
}
if (todosHTML === "") { //if todosHTML is an emtpy string
todosHTML = "<li>Nothing todo...</li>"; //display the list
}
todosEl.innerHTML = todosHTML; //assign todosHTML to an html element
updateRemoveBtn(); //call updateRemoveBtn() function
function updateRemoveBtn() { //remove button function
var completedTodos = data.filter(function(todo){ //filter out the tasks that are done
return todo.done === true;
});
```
For the next line of code:
```javascript=
completedEl.textContent = completedTodos.length;
```
It means the "Remove" button will adopt the number of completed todo items (`completedTodos.length`) and print it as part of the text content of the button(i.e. "2 Remove")
The next line of code explains in which situation the "Remove" button will be disabled
```javascript=
if (completedTodos.length) {
completedEl.parentElement.disabled = false;
} else {
completedEl.parentElement.disabled = true;
}
}
```
If the`completedTodos.length` is zero (no completed todo items), the Remove button won't be disabled. Otherwise (`completedEl.parentElement.disabled = true;`) , the Remove button won't be clickable. The following screen shot might be a better illustration:


In both cases, no completed items, so in both pictures, the "Remove" button is disabled.
For the next function `onEnterKey(event)`, it is called when the user interacts with one of the interfaces. We will use comments to explain this function and forward:
```javascript=
if (event.code === "Enter") { //if the interaction was pressing "enter"
addTodoItem(); //call addTOdoItem function to add that task
```
The next function `validateTask(task)` is used to determine whether the input parameter is a valid string or not
```javascript=
function validateTask(task) { //
if (task !== "") { //if the string isn't empty
return true; //then it is valid
} else { //otherwise
return false; //invalid
```
The next function `addTodoItem()` will add new todo list items based on the user's input. Details are explained in comments:
```javascript=
function addTodoItem() {
if (!validateTask(inputEl.value)) { //calls the validateTask function to check and if it isn't, then the function will return nothing
return;}
var newTodo = { //new object
id: getTimeStamp() //the id assigned will be according to the time
};
newTodo.task = inputEl.value; //the task itself will be user's input
newTodo.done = false; //done will automatically be set to false
data.push(newTodo); //after storing all 3 properties, the object gets pushed into the data array
updateTodoItems(); //updateTodoItems function is called
resetInput(); //resetInput is called to reset the textbox
}
```
The next function is called when certain items are marked as complete:
```javascript=
function toggleComplete(event) {
var todoID = parseInt(event.currentTarget.id.replace('task-','')); //grab the current element that the user is interacting with and parse the ID into an int
var todoData = getTodoData(todoID); //call getTodoData and assign the object to todoData
todoData.done = !todoData.done; //set done property to the opposite of what it is
updateTodoItems(); //updateTodoItems is called to update the array
}
```
The next function removes the completed items and make the current list only have incompeted ones:
```javascript=
function removeTodoItem(event) { //called to remove a task
var incompleteTodos = data.filter(function(todo){ //filter out the tasks that are not finished
return todo.done === false;
});
data = incompleteTodos; //assign the originally data array to the new one.
updateTodoItems(); //update the list
}
```
The next function is used to reset the value of the user's input to an empty string:
```javascript=
function resetInput() { //called to reset the textbox
inputEl.value = ""; //by assigning it to an empty string
}
```
The next function is to find the item with a certain id in the data array:
```javascript=
function resetInput() { //called to reset the textbox
inputEl.value = ""; //by assigning it to an empty string
}
function getTodoData(id) { //called to grab the object when given an id
var todoFound; //empty variable
for (var i=0; i < data.length; i++) { //iterate through the entire data array
if (data[i].id === id) { //if the ids match
todoFound = data[i]; //assign the empty variable to the object that was found
// var indexAt = i;
break; //then break out of the loop
}
}
if (todoFound) { //if todoFound is not NULL
return todoFound; //return todoFound which is now assigned to the object
} else { //otherwise
return null; //return nothing/null
}
}
```
The last function, the helpr function, is used to assign an item in the data array an id based on the date and time.
:::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?
:::
We want to extend the functions of this program, to make it more user friendly.
We also noticed that there's a `function updateItemsLeft()` at the end of the javascript code. However, we want to make it more encouraging. Because most users not only use a todo list program to manage their plans, but also to become more organized, more efficient in general. To build a healthy new habit, encouragement and positive feedbacks are crucial. So, this is what we did:
(**The function will be called in `function updateTodoItems() `**)
```javascript=
function updateItemsLeftBetter() {
var completedTodos = data.filter(function(todo){
return todo.done === true;
});// this is a local variable that will return items that are already completed
var incompleteTodos=data.filter(function(todo){
return todo.done === false;
});// this is a local variable that will return items that are NOT done yet
if(completedTodos.length>incompleteTodos.length && incompleteTodos.length>0){
alert("Wow Keep it up! you are on fire");
};// if the user has more completed items than the incomplete ones, and there are still imcoplete tasks on the list, it will get an encouraging message
if (todosEl.textContent.includes('test')){
alert('you got this!');
}; // if the user's todo list include stressful content, such as "test", it will give another encouraging messages
if(incompleteTodos.length==0){
alert('well done!');// after I clicked the last task on my list, it will send the user a message of "well done".
}
}
```
There are a few screenshot of our demos:
> This is when the incomplete items is **LESS** than the completed ones [color=skyblue]

>This is when I enter something including the stress-trigering word "test"[color=skyblue]

>This is after I clicked "change hamster's padding", which is the last item on my list [color=skyblue][color=skyblue]
