for loops · حلقات for
Repeating with a for loop
- A loop runs the same block many times, so you don't repeat yourself.
for (let i = 1; i <= 5; i++) { ... }has three parts: starti = 1, testi <= 5, stepi++.
التكرار باستخدام حلقة for
- الحلقة تشغّل نفس الكتلة مرات عديدة، حتى لا تضطر للتكرار بنفسك.
for (let i = 1; i <= 5; i++) { ... }له ثلاثة أجزاء: بدءi = 1، اختبارi <= 5، خطوةi++.
for (let i = 1; i <= 3; i++) {
console.log(i); // → 1, then 2, then 3
}
Build a running total
- Keep a variable outside the loop and add to it on every pass.
بناء مجموع تراكمي
- احتفظ بمتغير خارج الحلقة وأضف إليه في كل دورة.
let total = 0;
for (let i = 1; i <= 10; i++) {
total = total + i;
}
console.log(total); // → 55
Trace the running total · تتبع المجموع الكلي
A loop repeats its body. Step through the passes and watch total grow. · الحلقة تكرر جسمها. مرّ عبر الدورات وشاهد total يكبر.
Watch out
i <= 5stops after 5;i < 5stops before 5. Picking the wrong one is the classic "off-by-one" bug.- Start the total at
0before the loop, not inside it.
انتبه
i <= 5تتوقف بعد 5؛i < 5تتوقف قبل 5. اختيار الخطأ هو خطأ "Off-by-one" الكلاسيكي.- ابدأ المجموع عند
0قبل الحلقة، وليس بداخلها.
Common mistakes
for (let i = 0; i < n; i++)runsntimes.- Declare the counter with
let, not without.
أخطاء شائعة
for (let i = 0; i < n; i++)تشغّلnمرة.- أعلن العداد بـ
let، وليس بدونها.
Now you try
- Use a
forloop. - Press Check answer to test it.
الآن جرب بنفسك
- استخدم حلقة
for. - اضغط على تحقق من الإجابة لاختبارها.
Use a for loop to log the numbers 1 to 5, one per line. · استخدم حلقة for لتسجيل الأرقام من 1 إلى 5، واحدًا لكل سطر.
Click Run to see the output here. · اضغط تشغيل لرؤية المخرجات هنا.
Use a for loop to add up 1 to 10, then log the total (it is 55). · استخدم حلقة for لجمع 1 إلى 10، ثم أخرج المجموع (وهو 55).
Click Run to see the output here. · اضغط تشغيل لرؤية المخرجات هنا.
Use a for loop to log the even numbers 2, 4, 6, one per line (step by 2 with i += 2). · استخدم حلقة for لتسجيل الأرقام الزوجية 2، 4، 6، واحدًا لكل سطر (بخطوة 2 مع i += 2).
Click Run to see the output here. · اضغط تشغيل لرؤية المخرجات هنا.