Loops
لم يُترجم بعد؛ يُعرض باللغة الإنجليزية
A loop runs the same lines again and again. Follow a five-line for loop that adds 1, 2 and 3: the start runs once, the check i <= 3 runs before every round, the body adds i to total, i++ runs after every round, and when the check turns false the loop ends and console.log prints 6.
5 أسئلة سريعة
اختر إجابة لتعرف السبب. تُحفَظ نتيجتك مع تقدّمك.
01In for (let i = 1; i <= 3; i++), which part runs only once?
The start, let i = 1, runs once before anything else. The check runs before every round and the update runs after every round.
02When does the body of a for loop run?
Before every round the engine works out the check. If it is true the body runs; the first time it is false the loop ends.
03Trace the loop. What are total and i just after round 2 (after i++)?
Round 1: total = 0 + 1 = 1, then i becomes 2. Round 2: total = 1 + 2 = 3, then i becomes 3.
04How many times is the check i <= 3 worked out in this loop?
Three times it is true (i = 1, 2, 3) and once it is false (i = 4). The false check is what ends the loop.
05What happens if you delete i++ from the loop?
Nothing changes i any more, so the check never becomes false. An endless loop keeps the page busy and it stops responding.
المسرد
- Loop
- Code that runs the same lines again and again, as long as a condition is true.
- Round (iteration)
- One pass through the body of a loop.
- Body
- The lines between the loop's curly braces { }: what runs in every round.
- Condition (check)
- An expression such as i <= 3 that is worked out to true or false before every round.
- Counter
- A variable, often called i, that counts the rounds and is changed by the update.
- i++
- The increment operator: adds 1 to i.
- Infinite loop
- A loop whose condition never becomes false, so it never ends.
- while loop
- A loop with only a check: while (condition) { body }. It repeats while the condition is true.
الملاحظات والمصادر
- The order of a for loop is: the start once; then the check; if true, the body and then the update; then the check again. MDN and the ECMAScript specification (ForBodyEvaluation) describe the same order.
- Because i is made with let in the for line, it only exists inside the loop. JavaScript even makes a fresh copy of i for every round (CreatePerIterationEnvironment in the specification), so code saved in one round keeps that round's i. The figure shows one box.
- Engines compile JavaScript to machine code as it runs. The result is the same as running each statement in order, which is how the figure shows it.
- In a browser, JavaScript runs on the page's main thread. A loop that never ends keeps that thread busy, so the page cannot react to clicks or redraw until the browser stops the script.
- The script is real: paste it into the browser console (or run it with Node.js) and it prints 6.
اختبار يتاح بعد الخطوة الأخيرة.