# TINKER - Javascript Part II > Yukari Kimura [name=yk2898] > Steve Sholdra [name=ss5524] > Fei Wang [name=fw2347] ## 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. 1. Adding a todo 2. Completing a todo 3. 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 toaster pops out the toast after the time is completed and goes “DING”. 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 - Making toast for a big family READ loaf of bread READ slide 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. :::info **Group Answer:** Adding a todo: * WRITE a new todo item in the text box * READ the new todo item added in the text box * WRITE the new todo item to the list Complete todo * IF a todo item is checked * READ the checked todo item * WRITE the item into gray color * WRITE the item with strikethrough * WRITE the item in italic * WRITE the circle of the item with circle completed * ELSE do nothing > Remove todo * IF an todo item is completed * WRITE the number of completed items in the remove button * WRITE red background color in the remove button * WRITE black color for the text and outline of the remove button * IF the remove button is clicked * remove completed todo item * WRITE original settings for the remove button * ELSE leave tasks completed * ELSE display tasks black/no italics/no strikethrough ::: >Adding a todo >* WRITE new todo >* READ text box input >* WRITE text box entry into ordered list >* WRITE entry as incomplete > >Completing a todo >* IF completed circle checked >* WRITE task as gray color >* WRITE task as strikethrough >* WRITE task as italicized >* ELSE >* do nothing > >Removing a todo(s) >* IF task completed >* READ all tasks completed >* enable Remove button >* WRITE number of completed tasks + "remove" >>* IF remove button selected >>* remove tasks from ordered list >>* ELSE leave tasks completed >* ELSE display tasks black/no italics/no strikethrough >[name=Steve] > > Adding a todo > > * Write TODO in the text field > * Add the item with ADD button > * A new TODO is added to the TODO column > >Completing a todo > >* When TODO is completed, click the checkbox of TODO item >* Completed TODO items are erased with a horizontal line and turn gray > >Removing a todo(s) > * Check the check button of the item you want to delete > * Click the delete button > * The item you want to delete in the TODO column is deleted > [name=Yukari] > Add todo > > * WRITE a new todo item in the text box > * READ the new todo item added in the text box > * WRITE the new todo item to the list > > Complete todo > > * IF a todo item is checked > READ the checked todo item > WRITE the item into gray color > WRITE the item with strikethrough > WRITE the item in italic > WRITE the circle of the item with a check mark ELSE nothing changes > > Remove todo > > * IF an todo item is completed > WRITE the number of completed items in the remove button > WRITE red background color in the remove button > WRITE black color for the text and outline of the remove button > IF the remove button is clicked > remove completed todo item > WRITE original settings for the remove button > [name=Fei] 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. :::info **Group Answer:** While pseudocode presents a more direct approach to organize one's thoughts for writing the actual code, pseudocode itself is also difficult to write given the limited keywords to use and the logic embedded in the task. However, the process of writing pseudocode help comprehend the actual code. ::: >Pseudocode is actually very hard to write - it's hard to think of a process in terms of coding steps using only a certain number of keywords. I think that the IF/ELSE statements are the easiest to conceptualize, but the READ and WRITE pseudocode was difficult to interpret when tryign to write the pseudocode without first examining the JS code itself.[name=Steve] >Although it is different from the actual source code writing method, the processing flow is explained with a writing method close to the writing method of the source code. Written in human language, it cannot be understood by a computer, unlike the source code. It can be used as a reference when writing the actual source code. >[name=Yukari] > The pseudocode helps you organize the logic and sequence of the events for the actual code. It is similar with the actual code in the way they call on different variables and elements to make a change. However, as I look at the actual code, I find that it often times uses more succinct language that simplfies the process. Meanwhile, pseudocode is more straightfoward to understand but it takes time to transfer it into the programming language to make an effect. [name=Fei] 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.) :::info **Group Answer:** Manipulating different parts of the code helps us see how the interface works and understand the relationships among the elements of the codes on JavaScript. We expecially examine the various functions on JavaScript and see how they are different and similar from each other. ::: >Although I grasped the concept of the pseudocode exercise, I was fascinated to see how the actual code was built within. My favorite part was seeing the `if (completedTodos.length)` if/else function as the way to determine if the remove button was enabled or disabled. If the `completedToDos` had a length, the disable order on the button would be false, and if there was no length of completed tasks, then the disable order on the remove button would be true. A fascinating way to enable/disable a button, it's a small thing but I'll hopefully be incorporating that in my own project! [name=Steve] >When an empty todo is added, I manipurated the operation "Please add a todo." alert is displayed by using if/else and alert function.[name=Yukari] > I manipulated the function `updateRemoveBtn` and changed `return todo.done` to `false`. After I changed it, the `remove` button is now showing the correct number of items completed, but the number of the remaining items. I decided to manipulate this part because it seemed interesting to find out the causal relationship between the events happening on the todo list and the change on the remove button. The `updateRemoveFtn` function is controlled by the variable of `completedTodos`, which connects the two parts together for a meaningful interaction. [name=Fei] ## Part 1: Variables, Functions, Arrays, and Events Explain the data variable. What does this data (and the data inside) represent conceptually? :::info **Group Answer:** As an array, the `data` represents the task items on the todo list. The data inside are specific properties and values of the objects inside of the array. ::: >It represents the three task items that are displayed by default on screen when the page is refreshed[name=Steve] >These represent the todo lists that has already been added. It reappears when the browser is refreshed.[name=Yukari] > The data variable is an array or object that stores different types of properties and values. On the todo list, the data variable sets the default characteristics for the todo items, including their `id`, name of `task`, and whether it's `done` or not. The variable can store different data types including string, number, etc. [name=Fei] If I wanted to access the second object, how would I do that in code? :::info **Group Answer:** `var secondObj = data[1];` you can access the second object by calling the array index. ::: > `var secondObj = data[1];`[name=Steve] > I agree with Steve. You can access it using the value in the variable. [name=Yukari] > `var secondObj = data[1];` Since array indexes start with `0`, the second object inside this array could be accessed using the numeric index `1` as `data[1]`. [name=Fei] If I wanted to access the done property of the first object, how would I do that? :::info **Group Answer:** You can define a variable `doneFirstObj` with `data[0].done`. ::: > `var doneFirstObj = data[0].done` [name=Steve] >`Data[0].done` [name=Yukari] > `var doneFirstObj = data[0].done` or `var doneFirstObj = data[0]["done"]`. Object properties can be accessed through dot notation or bracket notation. [name=Fei] 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? :::info **Group Answer:** We have different opinions regarding whether you are manipulating the visual display or the data to update one of the other. ::: >I think you're manipulating the visual display - this is a big step forward from the previous weeks of coding, so it's more complex, but I believe the visual display is being updated, since the original data array is not being manipulated. New data arrays are being shown with the updated input. [name=Steve] >The visual display is manipulated first, and then the data is undated to reflect those changes. [name=Yukari] >I think you are manipulating the data to update the visual display to reflect changes. Looking through the JS code, I find that you are accessing and manipulating the different values of the data to change the visual display, which reflects the manipulation of data. I believe the original data array has not been changed, but the execution of functions would create new looks on them. [name=Fei] > Is this what you would have thought of? :::info **Group Answer:** We find it a little tricky to fully understand the causal relationship between data and visual display. However, it makes sense to data are used to make bigger changes and visual displays are used to reflect the change. ::: >To be honest, if I'm wrong about the prior question, then this will be wrong - but that's what learning is all about, trying to solve things to the best of our ability! I wouldn't have thought of manipulating the data and *then* updating the visual display. [name=Steve] > >Yes. [name=Yukari] >Yes, to me it makes sense to manipulate the existing properties and values to update or create a new visual display. [name=Fei] What might be the significance of this program design decision? :::info **Group Answer:** It preserves the original data so that if anything happens you can still go back to the beginning without having the data altered or damaged. ::: >This original data array is not being changed through the `filter` method - rather, it's updating and creating a new array. This impacts the program because the data array is pre-built with the original three items, and resets to that every time the program is opened. [name=Steve] >It is designed to save you time updating the visual display if the data changes later. [name=Yukari] >This program design decision helps programming be clean in a way that you are not polluting the original information or data. Therefore, if anything goes wrong, you can easily go back to the original state since you are not altering the data but only changing the display of them. [name=Fei] What do these lines in my code do? `var todosEl = document.querySelector('#todos');` :::info **Group Answer:** `QuerySelector` is used to detect what is inside of HTML that is associated with the id `todos`. It defines a new variable `todosEl` based on the selection. ::: >This is used as a variable to update the innerHTML in line 48.[name=Steve] >`QuerySelector` is used to be able to detect inside of HTML. This line detects `id=todos` in HTML, and it is used as a variable. [name=Yukari] > It is defining a `todosEl` variable by selecting the value associated with the id `todos` in HTML. [name=Fei] `var inputEl = document.querySelector('input');` :::info **Group Answer:** It detects the `input` value set in HTML and selects the associated value for the defined variable `inputEl`. It is used in the functions of adding new todo and resetting input. ::: >This is used as a variable in both the adding new todo item, and the reset input function.[name=Steve] >It detect input function, and it is used as a variable. [name=Yukari] > It is defining an `inputeEl` variable by selecting the `input` set in HTML. [name=Fei] `var completedEl = document.querySelector('#counter');` :::info **Group Answer:** This code detects id=counter in HTML and defines the `completedEl` variable by selecting the values in reference to the `id` of `counter` in HTML. ::: >This is looking up and referring to the span id of the following button in the HTML code: `<button onclick="removeTodoItem()"><span id="counter"></span> Remove</button>`[name=Steve] >This line detects `id=counter` in HTML. And it is used as a variable. [name=Yukari] >It defines the variable of `completedEl` by detecting the `#counter` id in HTML and selecting the associated action `onclick`. [name=Fei] Why declare these (see above) variables at the Global scope instead of in the functions? :::info **Group Answer:** These variables are declared at the global scope instead of in the function because they are used in the entire programming for various functions in multiple times. ::: >Because they're used as variables in multiple functions.[name=Steve] >These variables at the scope are used in JS for many times, so it is more easier way than defining the functions. [name=Yukari] >Becasue they are important elements that would be used as references for multiple places in JS functions. [name=Fei] 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? 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. console.log("SOME LABEL: ", dataToLog); :::info **Group Answer:** `event.currentTarget` is the element that registered the event, referring to the element to which the event is attached; whereas `event.target` is the element that initiated the event. ::: >event.currentTarget is the element that registered the event, whereas event.target is the element that initiated the event. However, with this specific case, I'm confused why we needed to use event.currentTarget.[name=Steve] >`event.currentTarget` returns the node to which the event is attached, and `event.target` returns the node where the event actually occurred. [name=Yukari] >`event.currentTarget` refers to the element to which the event handler has been attached, while `event.target` identifies the element on which the event occurred. [name=Fei] 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? :::info **Group Answer:** We think that it is the same as the id property in the todo objects in the data array,as the `event.currentTarget` is calling the id property in the data array. ::: >It is calling the id in the data array...but this part is confusing me. Along with many other parts of this week's tinker :smile: [name=Steve] >I think that it is same because `event.currentTarget` returns the node to which the event is attached. [name=Yukari] >I think the id in the `event.currentTarget.id` is calling the id property in the todo objects in the data array. [name=Fei] Explain. What does !something mean? (The exclamation mark) and how is it used in this code when we `toggleComplete`? :::info **Group Answer:** `!` means not, so when the function runs, the item will be completed on the todo list. ::: >It's the logical not, so since done is a boolean value (true/false), it's referring to the boolean state of `done`. [name=Steve] >It is used when the value of the operand is evaluated as "boolean" and then the value is inverted. [name=Yukari] >`!` means not. The original state for the `done` value is `false`, which makes this case to be the opposite as `true`. When the function is executed, the item will be completed and the todo list will be updated. [name=Fei] Try calling some of the functions directly from the console. Some will work. Some won’t. Explain what you find. Look at the function declarations in the todos.js file. Where is each function being called? :::info **Group Answer:** Most of the functions are called in JavaScript while a few are called through the `onclick` in buttons from HTML. ::: >Except for adding and removing to-do items (which are called through the button click in the HTML script), the functions are called within the other functions themselves in the JS code. They're co-dependent.[name=Steve] >Most functions are called from JS. [name=Yukari] >The functions are called through other functions on JavaScript and therefore they are interconnected. [name=Fei] When is each function, actually called? :::info **Group Answer:** Many functions are called from other functions defined in JavaScript. Some are called through the `event` handler that connects HTML with JavaScript. ::: >There are a few highlighted functions that caught my attention for unique reasons. 1) the `updateRemoveBtn()` function is called within the `updateTodoItems()` function, and identified directly below. 2) `onEnterKey(event)` is one of the many functions that uses the `(event.code === "Enter")` rule, which we learned in this week's FCC trainings. It's nice to see how it's used in real coding! 3) `updateTodoItems()` is called directly within the `initializeTodos()` function.[name=Steve] >The function `onEnterKey(event)` is called when adding new todo item and clicking the add button. [name=Yukari] >Most of the functions are called through the `if` `else` statements, which specifies the state when you call the specific function to run. For example, the function `validateTask` is called based on the result of the `if` statement. [name=Fei] What parameter(s) does that function have? :::info **Group Answer:** the `onEnterKey()` function has an `event` parameter, and the `validateTask()` function has a `task` parameter. ::: >The function `onEnterKey` has an `event` parameter. [name=Yukari] >I agree with Yukari, `onEnterKey` uses the parameter `event`. [name=Steve] >The function `validateTask` has a `task` parameter. [name=Fei] What is the argument that is passed into the function when it is called? :::info **Group Answer:** The `event.code === "Enter"` argument is passed in the `getEnterKey` function when it is called. The time represented by a sequence of number is passed into the function `getTimeStamp()` when the function is called. The argument `if(event.code === "Enter")` is passed int ::: >For `getEnterKey`, if the `event.code` is strictly equal to Enter, then the `addTodoItem` function will be called. There is no need for an `else` statement for this, since it is based on an `event` of enter.[name=Steve] >When the function `getTimeStamp()` is called, the long sequence of number is passed into the function. [name=Yukari] >For the `validateTask` function, the argument that is passed into the function when it is called is the `if(event.code === "Enter")`. [name=Fei] 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? `console.log(data);` `console.log(todosEl);` `console.dir(data);` `console.dir(todosEl);` :::info **Group Answer:** `console.log()` returns the object as a string without its original properties, while `console.dir` returns the object with more information including its properties and values. ::: >The log only shows the innerHTML, whereas the dir shows far more information, including: the innerText (like Jin discussed in this week's videos), the children/parent elements, and much more. [name=Steve] >When developing JavaScript, if you want to display the value of a variable on the console, use `console.log()` normally. The properties are displayed horizontally. Using `console.dir()` is convenient because the properties of objects are displayed in a horizontal + vertical direction. [name=Yukari] >`Console.log()` returns the object in the string representation, while `console.dir` returns the object just as the object with its properties and values preserved. Therefore, `console.dir` is more useful because it contains richer information. [name=Fei] ## 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. :::info **Group Answer:** There will be strikethrough for all items on the todo list when we change the `done` property. The content of the todo list for the specific task also changes when we change the `task` value. This happens because we manipulated the data and the results are reflected through the visual display. ::: >When I changed the done property to “true,” the strikethrough is added on TODO items in the list. Also, when I changed some of task values, the contents of TODO list were changed. I think the reason is that because the variable, `data elements` is in function `updateTODOItems()`.[name=Yukari] >After changing all of the `done` property to true, there is strikethrough for all items on the todo list. The text of the task changes when I change the `task` value as well. These changes occur because I changed the original data, which is reflected through the visual change. [name=Fei] >Since we're manipulating the data in the original array, the information is updated in the display screen as well.[name=Steve] 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? :::info **Group Answer:** A new object is added to the orginal array, with its corresponding `id`, `task`, and `done` properties in the data array. ::: >The array changes, and a new array is added with an id of a timestamp. It shows whether the new array task is completed or not (true or false) and the task name, which is based on the user input in the text field. [name=Steve] >The task of new todo is added and displayed. [name=Yukari] >A new object is added to the array with detailed properties and values added inside of the object based on the user input. A new `id` is generated and a new `task` value is written as a string value. Meanwhile, the `done` property for the new object is `false`, contrary to the others' `true` property since I just changed them for the last question. [name=Fei] Run the following code: data.push({ done: true, task: "Goto Aikido Lessons", id: getTimeStamp() }); console.dir(data); What did the code above do? :::info **Group Answer:** It adds a new task on the todo list since the data has a new task at the end of the array. ::: >It added a task directly into the data array [name=Steve] >Adding new task in TODO.[name=Yukari] >It adds a new item on the todo list as the data now is added with a new task at the end of the array. [name=Fei] Does our page reflect the changes made? Why or why not? Prove it. :::info **Group Answer:** Initially, the changes are only shown in the code, but once clicking on the items in the todo list, it triggers the functions that are associated with the `data` variable and the data array is updated. ::: >The viewer page does not reflect the change, but the console data does show the task in the array. [name=Steve] > >For me, I could see the reflection of adding task of `“Goto Aikido Lesson”` on TODO list.[name=Yukari] >The page reflects the chanegs made one I clicked on the items on the todo list. Otherwise it only shows on the data array. I think this is because clicking on the other items would trigger the functions that are associated with the `data` variable, which updates the data array. [name=Fei] Does order matter in Objects? :::info **Group Answer:** Yes! The visual display follows the order set in objects. ::: >Yes. [name=Steve] >Yes, it does.[name=Yukari] >Yes, the visual display follows the order set in objects. [name=Fei] What is the difference between Object keys (E.g. done, task, id) and Array indices (E.g. 0, 1, 2)? :::info **Group Answer:** *Object keys* are identifiers and specify the values stored in the objects. *Array indices* are used as references to call on certain objects, but don't have a value themselves. ::: >The object keys are identifiers, and they can be used as data lookup using dot or bracket indentation to identify the value that they hold (i.e. `.task` is "code". Indices do not have a sub-value, they just refer to the place in their index (i.e. `myAry[1]` returns 123. [name=Steve] >Array indices: refer to data stored using subscripts. Object key: refer to data stored using property.[name=Yukari] >Object keys: they specify the values stored in the objects; array indices: they are used as references to call on certain objects based on the index but don't have any value itself. [name=Fei] How are they similar? :::info **Group Answer:** They are both used to extract data in an easy way, but for different purposes. ::: >They are both used to look up data in objects, but for different purposes. [name=Steve] >Both refer to the data.[name=Yukari] >Both can be used to extract data in an easy way. [name=Fei] 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: 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(el); What is an element really? :::info **Group Answer:** An element is part of HTML code, and in this code, is a variable defined by selecting the values in the `<ul>` in HTML. ::: >It is a part of HTML code like `<p>` or `ul` or `<div>` or `<img>`. [name=Steve] >In this code, an element is “ul”.[name=Yukari] >In this case, an `element` is a variable defined by selecting the values in the unordered list in HTML. [name=Fei] How does our element relate in terms of similarities and differences to example? :::info **Group Answer:** Both elements come from `innerHTML`. `‘Input’` and `‘ul’` are tags, and `#todos` and `#counter` are `id` from `innerHTML`. ::: >Example returns the values of the object, whereas element returns the detailed underlying information about the object.[name=Steve] >Both elements come from `innerHTML`. `‘Input’` and `‘ul’` are tags, and `#todos` and `#counter` are `id` from `innerHTML`. [name=Yukari] > Both `element` and `example` are variables defined in JavaScript. However, `element` is defined by selecting certain detailed properties (in this case, the `ul`) in HTML, while `example` is defined by directly inserting values and a function on JavaScript. [name=Fei] If I wanted to call the function in the example object, how would I do that? Prove it. :::info **Group Answer:** We had difficulty on this question, but as a group, agreed on `console.dir(example.sayHello);`. ::: >This answer is not sure, but I think use `console.dir(example.sayHello);` ?? [name=Yukari] >I agree with Yukari that it should be `console.dir(example.sayHello);`. [name=Fei] >I had trouble with this one, but yes I agree with my teammates, `console.dir(example.sayHello);`. [name=Steve] 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? var x = "username"; var user = { username: "happyCat" } console.log(user.username); console.log(user["username"]); console.log(user[x]); console.log(user.x); :::info **Group Answer:** Bracket notation is more expressive, and it converts all property name into strings to retrieve corresponding property. The . object notation shows the meaning that the contents of something. ::: >I think the . object notation shows the meaning that the contents of something. E.g in the code, `user.username` means that `username` in `user`?[name=Yukari] >Bracket notation is more expressive than dot notation as it converts all property name into strings to retrieve corresponding property. [name=Fei] >Bracket notation is better in the "username" scenario because it will pull the string. Dot notation is best for the .x scenario because it is a variable (without a space).[name=Steve] 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. :::info **Group Answer:** `if (todo.done) {` the thing on the left side of the `.` is `todo`, which is a defined variable, while the thing on the right side of `.` is `done`, which is the property specified in the `data` array. Another example is console.log() - console is where the log is printed, and the log(xx.xx) is showing the indexed path of the object. ::: >Console is where the log is printed, and the log(xx.xx) is showing the indexed path of the object. [name=Steve] >`if (todo.done) {` the thing on the left side of the `.` is `todo`, which is a defined variable, while the thing on the right side of `.` is `done`, which is the property specified in the `data` array. [name=Fei] > 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? :::info **Group Answer:** Filter creates a new array with all of the elements that match the conditions and pass the test set in the function. ::: >`Filter()` uses a callback function for the elements in an array, and makes a new array with all of the values where the callback proves true. [name=Steve] >Create a new array with all elements of the array that match the conditions.[name=Yukari] >It creates a new array with all elements that pass the test set in the function. [name=Fei] What is the significance of the function argument that is passed INTO the filter parameters? :::info **Group Answer:** The filter creates an array filled with all of the elements that pass the test in the function. You can get the array of elements based on the filter set in the function, but the function passed into the filter parameters is not changed itself. ::: >The filter() creates an array filled with all array elements that pass a test that is determined in the function). [name=Steve] >The element of the array you want to call is passed into the filter parameters.[name=Yukari] >You can get an array of elements that you want based on the filter set in the function. THe function passed into the filter parameters is not changed itself. [name=Fei] 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? :::info **Group Answer:** Because the filter function returns only the elements that are determined to be `true` and adds them to a new array. ::: >Because the filter is based on whether a value is determined to be `true`. [name=Steve] >Because the filter function takes out only the elements that match the conditions and uses them when creating a new array.[name=Yukari] >Because this way the function `return` or not based on whether the `filter` function returns true or false. [name=Fei] 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? :::info **Group Answer:** It returns all array elements that are considered to be `true` in a newly created array. ::: >All array elements that are `true` based on the test in the function. [name=Steve] >The newly created array.[name=Yukari] >It returns a new array based on the `filter` function that selects elements that are `true`. [name=Fei] Does filtering an array change the original array? :::info **Group Answer:** No, it only selects elements and returns them in a new array. ::: >No. It makes a new array with all the values that are determined to be `true`, but doesn't change the original array. [name=Steve] >No, it does.[name=Yukari] >No, it only selects elements but not affects them. [name=Fei] ## Part 3 Control Structures I use the if statement in several places in this code. Explain why a conditional is necessary in: updateTodoItems :::info **Group Answer:** To judge whether the `todo` is complete or incomplete. ::: >To determine complete/incomplete [name=Steve] >It judges that if the `todo` is done or not.[name=Yukari] >To determine whether it is true that the item in `todo` is done. [name=Fei] updateRemoveButton :::info **Group Answer:** The strict equal operator condition `todo.done === true` is necessary to determine when to make the `return`. When the `todo` task is `done`, it will `updateRemoveBtn`. ::: >To return `todo.done` using the strict equal operator [name=Steve] >To remove if the completed `todo` is true.[name=Yukari] >The condition `todo.done === true` is necessary to determine when to make the `return`. When the `todo` task is `done`, it will `updateRemoveBtn`. [name=Fei] onEnterKey :::info **Group Answer:** To set the condition of when to run `addTodoItem` using the enter `event`. ::: >To run the function `addTodoItem()` if there is an event of `Enter` [name=Steve] >To add a todo item if it is written in text-box.[name=Yukari] >The function sets the condition of when to `addTodoItem`using the `"Enter"` `event`to call the function. [name=Fei] validateTask :::info **Group Answer:** If `task` is not blank, it returns `true`. ::: >Triggers if `task` is *not* equal to blank [name=Steve] >If `task` is not blank, return true.[name=Yukari] >If `task` does not have a blank value, return `true` to set the condition for the `validateTask` to run. [name=Fei] addTodoItem :::info **Group Answer:** If `validateTask` is false, it returns the input of a `todo` item value. ::: >If `validateTask` is not true (if it is false, then task is not blank) [name=Steve] >To input a todo item if the function `validateTask` works.[name=Yukari] >return the input of a `todo` item value if `validateTask` is false? [name=Fei] getTodoData :::info **Group Answer:** The `if` statement sets which data to get based on the `id` and add to the tasks if `todoFound` is true. ::: >To add to the list of tasks (also using i++) [name=Steve] >To get data and add to the tasks.[name=Yukari] >The if statements sets which data to get based on the `id` and what happens if `todoFound` is true. [name=Fei] HINT: You might want to console.log the boolean condition where you see the if statements to understand what condition we are evaluating. if (booleanCondition) { ... } console.log(booleanCondition); Comment on how the boolean condition works as there are many different examples. :::info **Group Answer:** As a group, we each identified different examples: * Because of the way `validateTask` was written, if the task input area is blank, then `validateTask` is true. * In the example, `onEnterKey`, if `event.code` is equal to ``“Enter”``, `addTodoItem()` runs. It means that if something is written in text-box, add button works. * `removeTodoItem()` uses the `filter()` function that gets values from other function. It also uses the strictly equal operator for the `done` property which has booleen values for setting the condition. ::: >The most interesting boolean condition that I found was the one mentioned above, `addTodoItem()`. Because of the way `validateTask` was written, if the task input area is blank, then `validateTask` is true. The `addTodoItem` works on the "not equal operator" condition that `validateTask` is true. I found this particular play on not-equaling-true fun to decipher the logic for! [name=Steve] >In the example, `onEnterKey`, if `event.code` is equal to ``“Enter”``, `addTodoItem()` runs. It means that if something is written in text-box, add button works. [name=Yukari] >`removeTodoItem()` uses the `filter()` function that gets values from other function. It also uses the strictly equal operator for the `done` property which has booleen values for setting the condition. [name=Fei] > > In this code, there are two kinds of for loops. The more traditional that looks like: for (var i=0; i < list.length; i++) { // CODE } and a for of loop that looks like: for (item of list) { // CODE } How does a for of loop work? :::info **Group Answer:** It sets a repeating process for the conditions that are satisfied to fun in the function, with statements that are executed for every distinct property of the object. ::: >It creates a loop for each part of the array, with statements that are executed for every distinct property of the object. [name=Steve] >* for ``(var i=0; i < list.length; i++)`` : Repeat the process written in ``{}``. >* for ``(item of list)`` : Repeat the process of `item` (value of property) of `list` (object).[name=Yukari] >It sets a repeating process for the conditions that are satisfied to fun in the function.the loop will run for each property or value that fulfills the condition. [name=Fei] What does the item represent? (It can be named anything: x, item, thing etc.) :::info **Group Answer:** It represents the value or property, and the loop iterates over each part of the iterable (like an array). ::: >The item is a variable part of some array, and the loop iterates over each part of the iterable (like an array). [name=Steve] >It represents the value of property.[name=Yukari] >It represents the property or the value in the list that are used as conditions in the loop. [name=Fei] Why are for of loops convenient compared to the traditional for? :::info **Group Answer:** Unlike `for` loops, `for of` loops directly access the array element and the information. Therefore it’s convenient. ::: >For loops give you the index of the array, not the element itself, so you have to use the `arr[i]` to access the array element. For of loops access the array element itself, so it accesses the information directly. [name=Steve] >It’s simple to write and easy to understand.[name=Yukari] >`for of` loops directly sets the location to which you are accessing the elements, while you have to further specify the condition in the `for` loop to work through certain times. [name=Fei] For what purpose(s) do I employ a for or for of loop in this program? :::info **Group Answer:** The `for` loops repeats a specified number of times. The `for of` loops through the value of an iterative object, and is used to directly access information within data array instead of using indices. ::: >The for of loop is used to access information within the data array, accessing the information directly instead of having to use the indices. [name=Steve] >To explain that for loop repeats a specified number of times, but for of loop repeats once for object that is supposed to be iterated.[name=Yukari] >`for` loops would go through the code a number of times while `for of` loops through the values of an iterative object. [name=Fei] On Facebook or Pinterest, or Twitter, how does a loop through data relate to the display of content? :::info **Group Answer:** We think this is used for timeline, when clicking on a video in a post it usually auto-replays itself as a loop, and when refreshing the page and new data appears on top but the remaining post stay listed below. ::: >I'm only guessing, but maybe when you refresh the page and new data appears on top but the remaining posts stay listed below? [name=Steve] >I think it’s used for Timeline on these app.[name=Yukari] >I think for social media like Facebook, if you click on a video in a post it usually auto-replays itself as a loop. [name=Fei] ## 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? 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(); } :::info **Group Answer:** Both have the same result, and we’ve found that this version uses the condition that if the data has no length, a "Nothing Do" script is displayed. Also, the original version uses a `for` loop to access information in the data array itself, and the function affects the visual display by manipulating the `todosHTML` variable. ::: >This version is using the condition that if data has no length, then it displays the "Nothing todo" script. The other original version uses the for of loop to access the information within the data array itself. [name=Steve] >After replacing it with this alternate, the checkboxes were disappeared. I think both work in same way. [name=Yukari] >Both have the same results but the original function affects the visual display by manipulating the `todosHTML` variable while this new function uses `liElement` variable to make changes. [name=Fei] 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? :::info **Group Answer:** Using timestsap for Todo IDs makes each ID unique, which makes it easier to work with our code and saves time defining it. ::: >Because the todo ids will always unique no matter the high simultaneous usage of the page? [name=Steve] >To save time to define todo ids.[name=Yukari] >The use of timestsap for todo `ids` ensures that each id would be unique and therefore easier to manipulate in the code. [name=Fei] Take a look at the incomplete functions markAllComplete and updateItemsLeft. Can you complete these and add the functionality to this app? ## 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? :::info **Group Answer:** * Step Into works if the function has steps, the debugger enters the next function, where it breaks line by line. * Step over works if the debugger executes the following function and suspends post processing because it works on a function basis, if a line contains a function, the function will be executed and the result returned without debugging each line. ::: >Step over works based on functions, so if the line contains a function, the function will be executed and the result returned without debugging each line. Step into works differently, because if there is a function, the debugger enters the function and continues debugging from there, line by line. [name=Steve] >* Step in Source code can be executed line by line. If a function is included, it jumps to that function and continues to be executed line by line >* Step over It is the same as executing the source code line by line, but if there is a function, that function is executed and jumps to the next line.[name=Yukari] >`step into` : debugger goes into the next function and breaks there; `step over`: debugger goes through the next function and breaks afterwrads. [name=Fei] 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? :::info **Group Answer:** The console prints the HTML code that contains an unordered list containing the specific IDs of the items in the to-do list and displays the list of task items. It also outputs the onclick event handler of the JavaScript ``toggleComplete ()`` function. ::: >It shows the HTML code and the list of task items [name=Steve] >The console print HTML.[name=Yukari] >It prints the HTML codes with the unordered list that contains specific `id` for the items on the todo list as well as the `onclick` event handler for the `toggleComplete()` function on JavaScript. [name=Fei] Highlight the variable inputEl on this highlighted blue line. Why does the console say inputEl is undefined? :::info **Group Answer:** We think because of ``<input type="text" onkeypress="onEnterKey(event)">`` or the code hasn’t been through the parts after = that defines the variable. ::: >I may have done this wrong, but it doesn't say it's undefined. It says `<input type="text" onkeypress="onEnterKey(event)">` [name=Steve] >Because `inputEL` includes `event` of innerHTML?[name=Yukari] >Because at this point the code hasn't been through the parts after `=` that defines the variable? [name=Fei] 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? :::info **Group Answer:** It represents has already been executed the code up to that line, but does not include it. ::: >It executes the code up to, but not inclusive of, that line. [name=Steve] >It represents code that has already executed.[name=Yukari] >The code that has already executed. [name=Fei] 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? 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? :::info **Group Answer:** Jump from if (line 32) to todosHTML on line 36. It keeps looping until it finishes examining the code and returns to the next line. ::: >It jumps from the if (line 32) to the todosHTML on line 36. It then gets stuck in the loop. [name=Steve] >It continues to loop.[name=Yukari] >It continues to run in the loop until it finishes examining the code and exits to the next line. [name=Fei] How does the debugger behave when you reach the a filter function call? :::info **Group Answer:** It navigates the filter function and displays the data. Then jump to the next function. ::: >It provides an additional breakpoint, deselected, at the data AND the filter points in the same line. [name=Steve] >After navigating through the `filter` function, it returned to the end of the above function.[name=Yukari] >It shows the data filtered and jumps to the next function after reaching the filter function call. [name=Fei] What does filter do and how does it work? :::info **Group Answer:** Creates a new array that contains all array elements that match the specified criteria in the filter. ::: >Filter creates an array with all array elements that pass a test. [name=Steve] >Create a new array with all elements of the array that match the conditions.[name=Yukari] >It creates a new array containing all elements in the specified array based on the filter condition. [name=Fei] ## Part X: Putting all together 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. Make it yours (group’s) 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? > Users would benefit from having this easy interactive program to help keep track of their projects. It's simple to add new items as many as they want to. [name-Fei] ```javascript var data = [ { id: 1497141891479, task: "Wake up", done: false }, { id: 1497141913701, task: "Eat breakfast", done: false }, { id: 1497141937545, task: "Learn code", done: true } ]; ``` :::info **Group Answer:** Var data has an array that identifies three objects. It has a numeric `id`, a string-valued `task`, and a Boolean completion field. The task is displayed in the TODO list. ::: >This is an array that identifies three objects. Each object in the array has an id with a numerical value, a task with a string value, and a done field with a boolean value. [name=Steve] >Var data has three objects. The tasks are displayed on TODO list.[name=Yukari] >This is a variable as an object or array that contains three objects inside including different properties and values.`id` are unique identifiers of each object as numeric values, `task` contains the string values of the item on the todo list, while `done` contains the boolean value of true or false. [name=Fei] ```javascript var todosEl = document.querySelector('#todos'); var inputEl = document.querySelector('input'); var completedEl = document.querySelector('#counter'); ``` :::info **Group Answer:** These three variables were created to detect the `id` `todos`, `input` and `counter`. ::: >This creates variables that pull from the id `todos`, `input`, and `counter` [name=Steve] > >Three variables are defined to detect `id` from innerHTML. [name=Yukari] >These three lines defined the varibales in JavaScript by selecting the associated elements based on the unique id in HTML `todos` `counter` and the `input` tag. [name=Fei] ```javascript function initializeTodos() { updateTodoItems(); } ``` :::info **Group Answer:** This function ``initializeTodos ()`` is a function to start the program. Call the ``updateTodoItems ()`` function. ::: >This is a function that starts the application. It calls the `updateTodoItems()` function. [name=Steve] > >This function `initializeTodos()` calls `updateTodoItems()`[name=Yukari] >This is defining a function `initializeTodos` to start the program. It calls the function `updateTodoItems`. [name=Fei] ```javascript function updateTodoItems() { var todosHTML = ""; for (todo of data) { if (todo.done) { todosHTML += `<li id="${ todo.id }" class="complete" onclick="toggleComplete(event)">`; todosHTML += `<i class="fa fa-check-circle-o"></i>`; // Font-awesome } else { todosHTML += `<li id="${ todo.id }" onclick="toggleComplete(event)">`; todosHTML += `<i class="fa fa-circle-o"></i>`; // Font-awesome } todosHTML += `${ todo.task }`; todosHTML += `</li>`; } if (todosHTML === "") { todosHTML = "<li>Nothing todo...</li>"; } todosEl.innerHTML = todosHTML; updateRemoveBtn(); } ``` :::info **Group Answer:** This function uses a `for` loop of if/else and if statements to determine when to modify the output of `todosHTML` which is updated based on the events and attributes set in the HTML. Then decide what to display in the todo list itself. Also, when todo is completed, it is displayed with strikethrough. If there are no tasks, the TODO list will display ``"Nothing to do..."``. ::: >This is a function that updates and changes the display of the `todoHTML` variable. With a for loop of if/else and if statements, it determines what displays on the to-do list itself. [name=Steve] >This function `updateTodoItems()` works how TODO list shows on the display. For example, If todo is done, it’s displayed with strikethrough. If there is no tasks, TODO list shows `“Nothing todo…”`. [name=Yukari] >This function is defined as a way to update to todo items on the list by manipulating the `todosHTML` variable. It uses the if statements to determine when to change the output of `todosHTML` to be updated based on events and attributes set in HTML. [name=Fei] ```javascript= function updateRemoveBtn() { var completedTodos = data.filter(function(todo){ return todo.done === true; }); completedEl.textContent = completedTodos.length; if (completedTodos.length) { completedEl.parentElement.disabled = false; } else { completedEl.parentElement.disabled = true; } } ``` :::info **Group Answer:** Use the filter function to create a new array to identify and display completed todos. It also uses this variable to define a function that updates the delete button on the todo list. ::: > This function determines if the remove button is displayed. By identifying a variable of completed todos, it filters and creates a new array of elements to display. [name=Steve] >The function `updateRemoveBtn()` has a variable completedTodos. It works when a todo task is completed. [name=Yukari] >The function is defined to update the remove button on the todo list. It uses the `filter` function to control the condition for the function and filters elements when a todo item is completed to be a variable of `completedTodos`. It then uses this variable to determine the display of the text. [name=Fei] ```javascript= function onEnterKey(event) { if (event.code === "Enter") { addTodoItem(); } } ``` :::info **Group Answer:** This function uses the event and calls the `addTodoItem` function when something is written to the text box. This is when ``.event.``code is exactly equal to Enter. Also, because it's based on the Enter `event`, you don't have to write any else statement code. ::: >Using an event, there is an if conditional. If the event.code is strictly equal to Enter, then the addTodoItem function will be called. There is no need for an else statement for this, since it is based on an event of enter. [name=Steve] > >This function works if event that something is written in text-box, and it is added on TODO list by `addTodoItem()`.[name=Yukari] >If certain texts are entered into the textbox, it will trigger the event and call the function `addTodoItem()`. [name=Fei] ```javascript= function validateTask(task) { if (task !== "") { return true; } else { return false; } } ``` :::info **Group Answer:** This ``validateTask ()`` function is defined using an if else statement. That means checking if the task field is empty. Returns true if the task is not "blank". Otherwise it returns false. ::: >This function checks if the task field is empty. If the task does *not* equal blank, then the return boolean value is true. Else, the returned boolean value is false. [name=Steve] > >This function inspects if an user enters task or not. If task is not equal to “blank,” return true.[name=Yukari] >This `validateTask()` function is defined using an `if else` statement. If the task does not have a blank input, it will return true. [name=Fei] ```javascript= function addTodoItem() { if (!validateTask(inputEl.value)) { return; } var newTodo = { id: getTimeStamp() }; newTodo.task = inputEl.value; newTodo.done = false; data.push(newTodo); updateTodoItems(); resetInput(); } ``` :::info **Group Answer:** This function checks if the function `validateTask` on the value of the variable `inputEl` is not true. If `validationTask` is not true, add a new variable `newTodo` with an id assigned. Then a new task is added. The data is pushed to a new todo with ``data.push (newTodo)``. Then the update function is called and then the reset input function is called. ::: >This function checks if the function `validateTask` of the value of the variable `inputEl` is *not* true. If it meets this condition, it returns. Then, a variable is identified and creates an id based on the `getTimeStamp` function of milliseconds. >Then, the task is changed of the new todo to match the inputEl value, and the new todo "done" boolean value is set to false (so this new task is unchecked). >Then, the data is pushed to the new todo. After this, the update function is called, and then the reset input function. [name=Steve] > >In the codes, if `validationTask` is not true, return undefined. If it’s true, a new task is added. The variable `newTodo` gets a timestamp as `id`. `data.push(newTodo)` shows that new task is pushed into variable `data`. [name=Yukari] >If `validateTask()`function returns false, add a new variable `newTodo` with its `id` assigned based on the `getTimeStamp` function. Then, it's adding the `task` and `done` values for this newly created todo item. `data.push(newTodo);` would put this new todo item at the last in the data array. Then the todo item is updated by including the new object in the array and input in the textbox is reset to be blank. [name=Fei] ```javascript= function toggleComplete(event) { var todoID = parseInt(event.currentTarget.id); var todoData = getTodoData(todoID); todoData.done = !todoData.done; updateTodoItems(); } ``` :::info **Group Answer:** This function determines whether to mark task checkboxes as complete or incomplete based on the todoData completion value. ::: >This is a function that determines whether tasks are marked complete or incomplete. [name=Steve] > >This function is to toggle task checkboxes between complete and incomplete.[name=Yukari] >This function defines when to switch between the complete and incomplete of the checkboxes based on the `todoData` `done` values. [name=Fei] ```javascript= function removeTodoItem(event) { var incompleteTodos = data.filter(function(todo){ return todo.done === false; }); data = incompleteTodos; updateTodoItems(); } ``` :::info **Group Answer:** This function uses the `todo` function to create a variable that filters the data. Use the filter function to get the appropriate data information. Call the ``updateTodoItems()`` function and the variable `data` will be updated as the variables identified above. When the todo function is called, the todo list is displayed after updating. ::: >This function creates a variable that filters the data, with a function of todo, returning the todo "done" variable to incomplete (a boolean value of false). The variable data is then updated as the variable identified above, and the update todo function is called. [name=Steve] > >This function shows if a todo task is not completed, the remove button doesn’t work, and incompleted tasks are still on TODO list.[name=Yukari] >This function is similar to the `updateRemoveBtn()` in using the filter function to obtain appropriate data information to set the variable `incompleteTodos..`However, it also callse on the `updateTodoItems()` function as part of this new function to display the todo list after updated. [named=Fei] ```javascript= function resetInput() { inputEl.value = ""; } ``` :::info **Group Answer:** This function sets the textbox input to blank. ::: >This function sets the value of the inputEl variable to blank. [name=Steve] > >This function runs when an user input empty.[name=Yukari] >This function is defined to set the input value of the textbox to be blank when executed. [name=Fei] ```javascript= function getTodoData(id) { var todoFound; for (var i=0; i < data.length; i++) { if (data[i].id === id) { todoFound = data[i]; indexAt = i; break; } } if (todoFound) { return todoFound; } else { return null; } } ``` :::info **Group Answer:** Search and retrieve the content of the data to be transferred based on the `id`. When `todoFound` finds the data, it returns that data. If not found, it returns null. ::: > This function gets the contents of the data being transferred. Specify the type of data to be acquired. [name=Yukari] >This function uses `for` loop and`if` `else` statements to set the conditions of running the function. It retrieves the data based on the unique `id` and then defines the variable `todoFound`. In the `for` loop, data is extracted by looping for a number of time until it reaches the number of objects in the data array. If `todoFound` has the associated `data` item, the function returns the found data, which includes the various values of the object, as the output. If not, it returns `null` to signal no todo item is found. [name=Fei] >This function looks for the data that's entered and adds the item to the to-do list. If it finds data to pull, then the function returns the new data. [name=Steve]