Computer ScienceChapter 3: Programming Fundamentals
3.3.1 Arrays in JavaScript
A JavaScript array
Explanation level
Definition
A JavaScript array is a special variable that can hold more than one value at a time. It is a collection of items stored in a single container, where each item can be accessed by its index number.
Main Idea
JavaScript arrays are a good way for organizing sets of similar data as they allow storing numerous values in a single container.
Core Concept
Let's say to store names of fruits, distinct variables for every fruit type will look like:
- "apple" be fruit1
- "banana" be fruit2
- "orange" be fruit3
- etc.
Alternatively, you may keep every fruit in a single variable by using an array. Creating an array will look like this:
```javascript const fruits = ["apple", "banana", "orange"]; ```
A JavaScript array's index is used to access each element and starts at 0. This indicates that the index of the first element is 0, the index of the second element is 1, and so on.
As stated above, our array is named 'fruits' and contains the words "apple", "banana", and "orange". Every object has an index number where the object is placed in the array:
- "apple" is placed at index 0
- "banana" at index 1
- "orange" at index 2
In JavaScript, an array can store various types of data, such as alphabets, numbers, or a combination of both.
Detailed Explanation
Traversing an Array with Loops
To traverse elements of an array and if the same operation needs to be applied on several components, loops are used. To demonstrate the use of a loop that iterates through every item in the 'fruits' array and outputs the result to the console:
```javascript for (let i = 0; i < fruits.length; i++) { console.log(fruits[i]); } ```
Key Points about Arrays
- You may use `push()` to add more items to the end and `pop()` to remove items from the end.
- Use `length()` to find out how many items are in the array.
- To go through everything in the array, you can use a `for-loop`.
- JavaScript arrays are flexible in a sense that they can expand or contract to accommodate additions or deletions of items.
- JavaScript does not require that every element in an array be of the same type, as compared to several other programming languages. Hence, different types of data can be combined in a single array.
- Arrays are a good tool to manage groups of data in JavaScript code.
Example: Sum of First 10 Positive Integers
Let us start with a simple program to calculate the sum of the first 10 positive integers using a for-loop. Thereafter, it stores the integers in an array using the `push()` function and later prints these numbers and the sum.
```html <!DOCTYPE html> <html> <head> <title>Sum of First 10 Integers</title> </head> <body> <script> function calculateSum() { let sum = 0; let numbers = [];
for (let i = 1; i <= 10; i++) sum += i; numbers.push(i);
document.getElementById("sumDisplay").textContent = "The sum of the first 10 integers is: " + sum;
let output = "The first 10 integers are: ["; for (let i = 0; i < numbers.length; i++) { output += numbers[i]; if (i < numbers.length - 1) { output += ", "; } } output += "]"; document.getElementById("numberDisplay").textContent = output; } </script>
<button onclick="calculateSum()">Calculate Sum</button> <br> <p id="numberDisplay"></p> <p id="sumDisplay"></p> </body> </html> ```
Explanation:
- On line 9, we define a function namely `calculateSum()`, in which a for-loop is executed starting from 1 till 10.
- On line 14, a variable `sum` which has an initial value of zero, is added with the index `i`. This way, by the time the loop terminates, we will have the sum of all the ten numbers stored in variable `sum`.
- A notable point is the next line where the index is stored in the array using the `push()` function, which will always append (add to the existing) array value of `i`.
Output: ``` The first 10 integers are: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] The sum of the first 10 integers is: 55 ```
Example: Shopping List
The next code shows how to use a JavaScript array to handle a shopping list. The array keeps track of the item names, and the functions in the code handle adding new items and updating the list on the webpage automatically.
```html <!DOCTYPE html> <html lang="en"> <head> <title>Shopping List</title> <style> table { border-collapse: collapse; width: 100%; } th, td { padding: 10px; border: 1px solid lightgray; text-align: left; } </style> </head> <body> <h1>My Shopping List</h1> <input type="text" id="newItem" placeholder="Enter item name"> <button onclick="addItem()">Add Item</button> <br> <table id="shoppingListTable"></table>
<script> let shoppingList = [];
function addItem() { const newItemName = document.getElementById("newItem").value;
if (newItemName != "") { shoppingList.push(newItemName); document.getElementById("newItem").value = ""; updateShoppingListTable(); } else { alert("Please enter an item name!"); } }
function updateShoppingListTable() { const table = document.getElementById("shoppingListTable"); table.innerHTML = "";
const headerRow = document.createElement("tr"); const headerItem = document.createElement("th"); headerItem.textContent = "Shopping List Items"; headerRow.appendChild(headerItem); table.appendChild(headerRow);
for (let i = 0; i < shoppingList.length; i++) { const itemRow = document.createElement("tr"); const itemCell = document.createElement("td"); itemCell.textContent = shoppingList[i]; itemRow.appendChild(itemCell); table.appendChild(itemRow); } } </script> </body> </html> ```
Explanation:
- The webpage has a heading, an add-item button, a text box where you may write the products, and a table that shows your shopping list.
- We maintain the list using JavaScript:
- The items are being added in an array we call `shoppingList`.
- The `addItem()` function is activated upon clicking the "Add Item" button, which checks to see if the box has entered text that is then added to the `shoppingList`, and the box is cleared to be rewritten.
- After that, the new item is then shown in the table by using a different function called `updateShoppingListTable()`.
- Additionally, a top row labeled "Shopping List Items" is also visible.
- Lastly, it adds each item to a new row in the table by going through the `shoppingList` one by one.
- In this manner, any chosen item to be purchased is added to the table.
Major Functions Associated with Arrays in JavaScript
| Function | Purpose | Example | Output |
|---|---|---|---|
| `push()` | Adds value at the end of the array | `oddNumbers.push(11);` | Initial: 1,3,5,7,9 → After: 1,3,5,7,9,11 |
| `indexOf()` | Searches for and locates the given element | `oddNumbers.indexOf(11);` | Index of last added number (11): 5 |
| `toString()` | Converts all elements into a single string | `combinedArray.toString();` | 1,3,5,7,9,11,2,4,6,8,10 |
| `concat()` | Merges 2 arrays | `oddNumbers.concat(evenNumbers);` | 1,3,5,7,9,11,2,4,6,8,10 |
| `slice()` | Creates a new subset array | `oddNumbers.slice(2,4);` | 5,7 |
Intermediate Level
At the intermediate level, you should understand the key operations.
Creating an array: ```javascript const numbers = [1, 2, 3, 4, 5]; ```
Accessing elements: ```javascript numbers[0] // 1 numbers[4] // 5 ```
Adding elements: ```javascript numbers.push(6); // [1, 2, 3, 4, 5, 6] ```
Removing elements: ```javascript numbers.pop(); // [1, 2, 3, 4, 5] ```
Finding length: ```javascript numbers.length; // 5 ```
Looping through: ```javascript for (let i = 0; i < numbers.length; i++) { console.log(numbers[i]); } ```
Important Points
- - An array is a collection of items stored in a single variable.
- - Arrays use index numbers starting from 0.
- - Arrays can store different data types.
- - `push()` adds to the end; `pop()` removes from the end.
- - `length()` gives the number of items.
- - `for-loop` is used to traverse arrays.
- - `indexOf()` finds the index of an element.
- - `concat()` merges arrays.
- - `slice()` extracts a portion.
- - `toString()` converts array to string.
Remember
- - Array = collection of items.
- - Index starts at 0.
- - 0 = add to end.
- - 0 = remove from end.
- - 0 = number of items.
- - 0 = traverse.
- - 0 = find index.
- - 0 = merge.
- - 0 = extract.
- - 0 = to string.
Common Mistakes
- - Forgetting that array indices start at 0, not 1.
- - Using `length()` instead of `length` (length is a property, not a function).
- - Confusing `push()` (add to end) with `unshift()` (add to beginning).
- - Confusing `pop()` (remove from end) with `shift()` (remove from beginning).
- - Trying to access an index that does not exist (returns `undefined`).
- - Forgetting that arrays can hold different data types.
- - Using `=` instead of `==` or `===` in conditions.
Quick Revision
- JavaScript array: collection of items in a single variable.
- Index starts at 0.
- Can store different data types.
- `push()` adds to end; `pop()` removes from end.
- `length` gives number of items.
- `for-loop` traverses elements.
- `indexOf()` finds index; `concat()` merges; `slice()` extracts; `toString()` converts to string.
- Arrays are dynamic and can grow/shrink.
60-Second Revision
- Array = collection of items.
- Index starts at 0.
- 0 = add end; 1 = remove end.
- 0 = count.
- 0 = traverse.
- `indexOf()` = find; `concat()` = merge; `slice()` = extract; `toString()` = string.
- Warning: Array indices start at 0, not 1. Also, `length` is a property, not a function.
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.1 Arrays in JavaScript
Sticky Notes · Quick Revision
Key Point 1
- Array = collection.
Key Point 2
- Index starts at 0.
Key Point 3
- 0 = add end.
Key Point 4
- 0 = remove end.
Key Point 5
- 0 = count.
Key Point 6
- 0 = traverse.
Key Point 7
- 0 = find.
Key Point 8
- 0 = merge.
Key Point 9
- 0 = extract.
Key Point 10
- 0 = string.
Same supplied content as this Notes page (shared canonical source).