Computer ScienceChapter 3: Programming Fundamentals
3.3.3 Bullet Points can be Values from Arrays
Bullet Points from Arrays
Explanation level
Introduction
The next example demonstrates how to create dynamic web page features with JavaScript and arrays. The code creates a simple shopping list to which users may add new items. The `shoppingItems` JavaScript array contains the list of items. The content of the array is used by the `updateList()` method to create the list. Any modifications made to the array are therefore reflected in the list.
Definition
Bullet Points from Arrays refers to the technique of using a JavaScript array to store data and dynamically generating an HTML list (`<ul>` or `<ol>`) from the array elements. This allows the list to update automatically when the array changes.
Main Idea
Instead of hard-coding list items in HTML, we store them in a JavaScript array. Then, using JavaScript, we loop through the array and create list items (`<li>`) dynamically. This makes the list dynamic — it changes when the array changes.
Core Concept
The process involves:
- Creating an array with initial values.
- Writing a function that clears the existing list.
- Looping through the array.
- Creating a new `<li>` element for each array item.
- Appending the `<li>` to the `<ul>` or `<ol>`.
- Calling the function whenever the array changes.
Detailed Explanation
Example: Dynamic Shopping List
The code creates a simple shopping list to which users may add new items.
```html <!DOCTYPE html> <html> <head> <title>Shopping List</title> </head> <body> <h1>My Shopping List</h1> <ul id="shoppingList"></ul>
<script> const shoppingItems = ["Milk", "Bread", "Eggs", "Apples"];
function addItem() { const newItem = document.getElementById("newItemInput").value; shoppingItems.push(newItem); updateList(); }
function updateList() { const listElement = document.getElementById("shoppingList"); listElement.innerHTML = "";
for (let i = 0; i < shoppingItems.length; i++) { const item = shoppingItems[i]; const listItem = document.createElement("li"); listItem.textContent = item; listElement.appendChild(listItem); } }
updateList(); </script> <br> <input type="text" id="newItemInput" placeholder="Enter new item"> <button onclick="addItem()">Add Item</button> </body> </html> ```
Explanation:
- The webpage has a heading "My Shopping List", an empty list that displays the items in bullet points, a box where you can enter additional items, and an "Add Item" button.
- The `shoppingItems` list defined on line 9 in this code maintains a record of all that we add.
- The `addItem` function is activated upon clicking the "Add Item" button.
- The text we entered in the box is added to the `shoppingItems` list by this function.
- The `updateList` method on line 17 is then called in order to ensure that the new item is displayed in our list on the webpage.
Understanding Functions
A block of code which is repeatedly used for a particular operation is called a function. A function may be defined once and called several times in the program, which simplifies code and decreases lines-of-code.
When defining a function, the `function` keyword is used followed by the name of the function and parenthesis for any input parameters.
The code for the function is enclosed in curly brackets. The function `updateList` locates every item on the web page and removes any content that is already there. Subsequently, it iteratively moves through the `shoppingItems` list, converting each item to a bullet point and appends it to the list displayed on the website. In this way, any purchase is constantly added to the list.
Step-by-Step Breakdown
- To store shopping goods, create an array called `shoppingItems`.
- `listContent` (string): This is how the shopping list is put together for presentation.
- The item to be searched for is held in `itemName` (string).
2. Enlisting Shopping List (the initial Loop): - Iterate `shoppingItems` array using a loop.
- Update the `listContent` string with the current item.
- If this is not the final item, separate it with a comma and leave space.
- Using the entire `listContent` string, update the HTML section with the ID "list".
- Search for an item by going over everything in the `shoppingItems` array.
- Inside the loop: Verify that the item we now have matches the `itemName` that we are searching for.
- If a match is discovered, use return to end the loop and update the HTML section with the ID "result" and a message indicating the item is found.
- Update the HTML code in the section with the ID "result" with a notification indicating the item is not found if the loop concludes without finding a match.
5. Using the Algorithm: - To begin, call the `findItem` method and search the required `itemName`.
Intermediate Level
At the intermediate level, you should understand how the JavaScript interacts with HTML.
Key steps:
1. Get the list container: ```javascript const listElement = document.getElementById("shoppingList"); ```
2. Clear the list: ```javascript listElement.innerHTML = ""; ```
3. Loop through the array: ```javascript for (let i = 0; i < shoppingItems.length; i++) { ```
4. Create a list item: ```javascript const listItem = document.createElement("li"); listItem.textContent = shoppingItems[i]; ```
5. Append to the list: ```javascript listElement.appendChild(listItem); ```
Important Points
- - Arrays can store list items.
- - JavaScript can dynamically create HTML lists from arrays.
- - `document.createElement("li")` creates a list item.
- - `appendChild()` adds the list item to the list.
- - `innerHTML = ""` clears the list before updating.
- - Functions make the code reusable and organized.
- - Changes to the array are reflected in the list.
Remember
- - Array = data storage.
- - List = visual display.
- - `createElement("li")` = create list item.
- - 0 = add to list.
- - 0 = clear list.
- - Function = reusable code.
- - Array changes → list updates.
Common Mistakes
- - Forgetting to clear the list before updating (causes duplicates).
- - Forgetting to call the update function after adding an item.
- - Using `innerHTML` instead of `textContent` (security risk).
- - Not creating a new `<li>` for each item.
- - Forgetting to append the `<li>` to the list.
- - Using the wrong ID when getting the list element.
- - Not handling empty input (adding empty items).
Quick Revision
- Bullet points can be generated from array values.
- `shoppingItems` array stores the items.
- `updateList()` function displays them as list items.
- `createElement("li")` creates a new list item.
- `appendChild()` adds it to the list.
- `innerHTML = ""` clears the list before updating.
- Changes to the array are reflected in the list.
60-Second Revision
- Array = data storage.
- List = visual display.
- 0 = create item.
- 0 = add to list.
- 0 = clear list.
- Function = reusable code.
- Warning: Always clear the list before updating to avoid duplicates.
Did you understand this topic?
Your answer is saved with your learning record. It does not mark the topic as mastered.
Quick revision
Revision Zone
Review the key facts, formulas and checks before you move on.3.3.3 Bullet Points can be Values from Arrays
Sticky Notes · Quick Revision
Key Point 1
- Array = data.
Key Point 2
- List = display.
Key Point 3
- 0 = create item.
Key Point 4
- 0 = add item.
Key Point 5
- 0 = clear list.
Key Point 6
- Function = reusable.
Key Point 7
- Array changes → list updates.
Same supplied content as this Notes page (shared canonical source).