topskill.dev
CoursesTracks
0
All courses/Introduction to JavaScriptFor Loops
Control Flow
10 / 17
← Introduction to JavaScript
○What is JavaScript?○Your First JavaScript Code○Data Types○Type Checking○Missing values and deliberate emptiness○Inspect Values in the Console○Inspect the Queue Report○Trace a Faulty Calculation○Repair the Score Calculation✦Module Quiz
○Declaring Variables○let and const in Practice○Operators○Type Conversion○Group and Convert Expense Inputs○Calculate the Event Expense Total○Track a Changing Points Tally○Adjust a Ticket Price✦Module Quiz
○Comparisons and strict equality○Truthiness and combined conditions○Function inputs and results○Conditionals○Combined Conditions Before FizzBuzz○Challenge: FizzBuzz Announcer○Switch Statement○Switch a Venue Sign○Challenge: Power Loadout●For Loops○While Loop○Break and Continue○Stop a Ticket Scan○Challenge: Number Guess Referee○Rainfall Routing Walkthrough○Score Batch Report✦Module Quiz
○Defining Functions○Arrow Functions○Scope○Closures○Project - Calculator○Function Expressions○Ticket Pricing Walkthrough○Shipping Labels with Defaults○Seat Ledger Closure Walkthrough○Private Budget Ledger✦Module Quiz
○Arrays○Student Scoreboard○Challenge: Student Course Scoreboard○Array Mutation Methods○Array Slice and Concat○Array Iteration Methods○Multidimensional Arrays○Destructuring○Array Reverse and Sort○Array Fill○Array Find and Includes○Array Flat and FlatMap○Array Reduce, Some, and Every○Charging Rack Restock Report○Pantry Restock Plan✦Module Quiz
○Object Key-Value Pairs○Student Course Record○Object Methods and Destructuring○Object copies and optional properties○Map and Set Collections○Playlist Lookup○Number and BigInt Boundaries○Ticket Ledger○JSON○Throwing and catching errors○Math and Date○Date Basics○Supply Bin Audit○Volunteer Shift Audit○Workshop Attendance Feed○Parcel Scan Feed✦Module Quiz
○String Methods○Template Literals○Regular Expressions○Build a Reminder with Template Literals○Format Pantry Pickup Messages○Validate a Time Slot with Regex○Validate Storage Shelf Labels✦Module Quiz
○Higher-Order Functions○Callbacks○map, filter, and reduce○Student Register with map○Challenge: Student Register○Recursion○Project - Data Transform Pipeline○Extend the inventory report○Handle an Error-First Callback○Report Seat Reservation Results○Summarize Completed Bike Rides○Summarize Delivered Parcels✦Module Quiz
○A notebook object○OOP Introduction○Independent workshop passes○Classes○An inherited notice○Inheritance○A private seat counter○Encapsulation○Equipment desk checkout○Project: Library Checkout✦Module Quiz
○Callback Timing○Asynchronous JavaScript○Promise Rehearsal○Promises and Async Await○Offline API Coordination○Async API Simulation○Partial Results Bulletin○Project: Resilient Awards Feed○Retry a Local Delivery○Project: Reliable Score Delivery✦Module Quiz

For Loops

A loop can visit each value in a list, adding to a total or collecting a new order.

Loops let you repeat a block of code. An array such as [2, 4, 6] is an ordered list; you will study arrays in depth later, but here you only need to visit its values. numbers.length counts entries, numbers[i] reads one entry (starting at index 0), and result.push(value) adds an entry to a new array. An empty array is written []. A const result array can still receive entries with push: const prevents assigning a different array to the name, not changing the contents of this one.

Traditional for loop

javascript
for (let i = 0; i < 5; i++) {
    console.log(i); // five separate lines: 0 through 4
}

Iterating an array:

javascript
const fruits = ["apple", "banana", "cherry"];
for (let i = 0; i < fruits.length; i++) {
    console.log(fruits[i]);
}

for...of — iterate values

Cleaner syntax when you only need the value, not the index:

javascript
for (const fruit of fruits) {
    console.log(fruit);
}

The fruits list here is the same list from the preceding example. If you copy this block into a new script, declare fruits first.

For the reverse task, start at arr.length - 1 (the last index), step backward with i--, and push each visited value into a new array. An empty array gives a sum of 0 because the loop runs zero times. Object-key iteration comes in the Objects module; it is not needed here.

A traditional for header has three parts: set up the counter once; check the condition before each pass; update the counter after each pass. i++ adds 1 and i-- subtracts 1. For a three-entry list, the valid indexes are 0, 1, and 2, so the forward condition uses < length, not <= length.

Keep the running total outside the loop body but inside the function. That gives each call a fresh total while allowing successive iterations to add to it. Return after the loop; returning inside it would stop at the first entry.

The starter prints lists by inserting them into template strings, which shows their values separated by commas. Brackets around the empty-list probe make an empty result visible as []. It safely prints [undefined] while the function is unfinished. You do not need to write or change the supplied probes.

Edit script.js, Run to inspect the supplied probes, and Submit to check the tasks.

Your Task

  1. Implement sumArray(numbers) with a for loop. Return the total, including 0 for an empty list; the supplied Sums line should show 2,15,10,0.
  2. Implement reverseArray(arr) with a backward for loop and a new result array. The supplied Reversals line should show 3,2,1 | c,b,a | [].
  3. Log Sum: 15 on its own line by calling sumArray([1,2,3,4,5]).
Hint 1
1 / 3
HINT 1

A standard for loop: for (let i = 0; i < arr.length; i++).

HINT 2

Use for...of to iterate values directly: for (const item of arr).

HINT 3

Accumulate a sum by adding each element to a total variable.

Files
  • ⋄script.js
Loading editor…
Press Run to execute your code.