diff --git a/1-js/02-first-steps/13-while-for/1-loop-last-value/solution.md b/1-js/02-first-steps/13-while-for/1-loop-last-value/solution.md index 43ee4aad3..60bb87a03 100644 --- a/1-js/02-first-steps/13-while-for/1-loop-last-value/solution.md +++ b/1-js/02-first-steps/13-while-for/1-loop-last-value/solution.md @@ -1,4 +1,4 @@ -The answer: `1`. +Răspunsul: `1`. ```js run let i = 3; @@ -8,18 +8,18 @@ while (i) { } ``` -Every loop iteration decreases `i` by `1`. The check `while(i)` stops the loop when `i = 0`. +Fiecare iterație descrește valoarea lui `i` cu `1`. Verificarea `while(i)` oprește iterația atunci când `i = 0`. -Hence, the steps of the loop form the following sequence ("loop unrolled"): +Așadar, pașii buclei formează următoarea secvență ("buclă desfășurată"): ```js let i = 3; -alert(i--); // shows 3, decreases i to 2 +alert(i--); // afișează 3, descrește valoarea lui i la 2 -alert(i--) // shows 2, decreases i to 1 +alert(i--) // afișează 2, descrește valoarea lui i la 1 -alert(i--) // shows 1, decreases i to 0 +alert(i--) // afișează 1, descrește valoarea lui i la 0 -// done, while(i) check stops the loop +// gata, verificarea while(i) oprește bucla ``` diff --git a/1-js/02-first-steps/13-while-for/1-loop-last-value/task.md b/1-js/02-first-steps/13-while-for/1-loop-last-value/task.md index 3b847dfa2..39cf808c9 100644 --- a/1-js/02-first-steps/13-while-for/1-loop-last-value/task.md +++ b/1-js/02-first-steps/13-while-for/1-loop-last-value/task.md @@ -2,9 +2,9 @@ importance: 3 --- -# Last loop value +# Ultima valoare a buclei -What is the last value alerted by this code? Why? +Care este ultima valoare afișată de acest cod? De ce? ```js let i = 3; diff --git a/1-js/02-first-steps/13-while-for/2-which-value-while/solution.md b/1-js/02-first-steps/13-while-for/2-which-value-while/solution.md index 495359876..7081fa99c 100644 --- a/1-js/02-first-steps/13-while-for/2-which-value-while/solution.md +++ b/1-js/02-first-steps/13-while-for/2-which-value-while/solution.md @@ -1,30 +1,24 @@ -The task demonstrates how postfix/prefix forms can lead to different results when used in comparisons. +Acest exercițiu demonstrează cum prefixele/sufixele pot duce la rezultate diferite când sunt comparate. -1. **From 1 to 4** +1. **De la 1 la 4** - ```js run - let i = 0; - while (++i < 5) alert( i ); - ``` + ```js run + let i = 0; + while (++i < 5) alert( i ); + ``` + Prima valoare este `i = 1` pentru că `++i` incrementează prima dată `i` și apoi returnează noua valoare. Așadar prima comparație este `1 < 5` și funcția `alert` afișează `1`. +2. **De la 1 la 5** - The first value is `i = 1`, because `++i` first increments `i` and then returns the new value. So the first comparison is `1 < 5` and the `alert` shows `1`. + ```js run + let i = 0; + while (i++ < 5) alert( i ); + ``` + Prima valoare este din nou `i = 1`. Forma cu sufix `i++` incrementează `i` și după returnează vechea valoare, deci comparația `i++ < 5` va folosi `i = 0` (față de `++i < 5`). - Then follow `2, 3, 4…` -- the values show up one after another. The comparison always uses the incremented value, because `++` is before the variable. + Dar funcția `alert` se apelează separat. Este altă linie de cod care se execută după incrementare și după comparație. Așadar primește `i = 0`. - Finally, `i = 4` is incremented to `5`, the comparison `while(5 < 5)` fails, and the loop stops. So `5` is not shown. -2. **From 1 to 5** + Apoi urmând `2, 3, 4...` - ```js run - let i = 0; - while (i++ < 5) alert( i ); - ``` + Hai să ne oprim la `i = 4`. Forma cu prefix `++i` l-ar incrementa și am folosi `5` pentru comparație. Dar aici avem forma cu sufix `i++`. Astfel îl incrementează pe `i` la `5`, dar returnează vechea valoare. Datorită faptului că comparația e de fapt `while(4 < 5)` - adevărat și execuția codului continuă cu funcția `alert`. - The first value is again `i = 1`. The postfix form of `i++` increments `i` and then returns the *old* value, so the comparison `i++ < 5` will use `i = 0` (contrary to `++i < 5`). - - But the `alert` call is separate. It's another statement which executes after the increment and the comparison. So it gets the current `i = 1`. - - Then follow `2, 3, 4…` - - Let's stop on `i = 4`. The prefix form `++i` would increment it and use `5` in the comparison. But here we have the postfix form `i++`. So it increments `i` to `5`, but returns the old value. Hence the comparison is actually `while(4 < 5)` -- true, and the control goes on to `alert`. - - The value `i = 5` is the last one, because on the next step `while(5 < 5)` is false. + Valoarea `i = 5` esre ultima, deoarece următorul pas `while(5 < 5)` este fals. diff --git a/1-js/02-first-steps/13-while-for/2-which-value-while/task.md b/1-js/02-first-steps/13-while-for/2-which-value-while/task.md index 298213237..cd573e81a 100644 --- a/1-js/02-first-steps/13-while-for/2-which-value-while/task.md +++ b/1-js/02-first-steps/13-while-for/2-which-value-while/task.md @@ -2,21 +2,21 @@ importance: 4 --- -# Which values does the while loop show? +# Ce valori afișează bucla while? -For every loop iteration, write down which value it outputs and then compare it with the solution. +Pentru fiecare iterație a buclei, scrie ce valori afișează și apoi compară-le cu soluția. -Both loops `alert` the same values, or not? +Ambele bucle afișează prin funcția `alert` aceleași valori, sau nu? -1. The prefix form `++i`: +1. Forma cu prefix `++i`: - ```js - let i = 0; - while (++i < 5) alert( i ); - ``` -2. The postfix form `i++` + ```js + let i = 0; + while (++i < 5) alert( i ); + ``` +2. Forma cu sufix `i++` - ```js - let i = 0; - while (i++ < 5) alert( i ); - ``` + ```js + let i = 0; + while (i++ < 5) alert( i ); + ``` diff --git a/1-js/02-first-steps/13-while-for/3-which-value-for/solution.md b/1-js/02-first-steps/13-while-for/3-which-value-for/solution.md index e2e28e75b..d88b195b0 100644 --- a/1-js/02-first-steps/13-while-for/3-which-value-for/solution.md +++ b/1-js/02-first-steps/13-while-for/3-which-value-for/solution.md @@ -1,4 +1,4 @@ -**The answer: from `0` to `4` in both cases.** +**Răspunsul: de la 0 la 4 în ambele cazuri.** ```js run for (let i = 0; i < 5; ++i) alert( i ); @@ -6,12 +6,12 @@ for (let i = 0; i < 5; ++i) alert( i ); for (let i = 0; i < 5; i++) alert( i ); ``` -That can be easily deducted from the algorithm of `for`: +Asta se poate deduce ușor din algoritmul lui `for`: -1. Execute once `i = 0` before everything (begin). -2. Check the condition `i < 5` -3. If `true` -- execute the loop body `alert(i)`, and then `i++` +1. Execută o dată `i = 0` înainte a orice altceva (inițializator). +2. Verifică condiția `i < 5` +3. Dacă e `true` -- rulează corpul buclei `alert(i)`, și apoi `i++` -The increment `i++` is separated from the condition check (2). That's just another statement. +Incrementarea `i++` e separată de verificarea condiției (2). Aceea e pur și simplu altă bucată de cod. -The value returned by the increment is not used here, so there's no difference between `i++` and `++i`. +Valoarea returnată după incrementare nu e folosită aici, așadar nu este nici-o diferență între `i++` și `++i`. diff --git a/1-js/02-first-steps/13-while-for/3-which-value-for/task.md b/1-js/02-first-steps/13-while-for/3-which-value-for/task.md index bfefa63f5..a89584e38 100644 --- a/1-js/02-first-steps/13-while-for/3-which-value-for/task.md +++ b/1-js/02-first-steps/13-while-for/3-which-value-for/task.md @@ -2,19 +2,19 @@ importance: 4 --- -# Which values get shown by the "for" loop? +# Ce valori se afișează pentru bucla "for"? -For each loop write down which values it is going to show. Then compare with the answer. +Pentru fiecare buclă, scrie ce valori se vor afișa. Apoi compară-le cu soluția. -Both loops `alert` same values or not? +Ambele bucle afișează prin funcția `alert` aceleași valori sau nu? -1. The postfix form: +1. Forma cu sufix: - ```js - for (let i = 0; i < 5; i++) alert( i ); - ``` -2. The prefix form: + ```js + for (let i = 0; i < 5; i++) alert( i ); + ``` +2. Forma cu prefix: - ```js - for (let i = 0; i < 5; ++i) alert( i ); - ``` + ```js + for (let i = 0; i < 5; ++i) alert( i ); + ``` diff --git a/1-js/02-first-steps/13-while-for/4-for-even/solution.md b/1-js/02-first-steps/13-while-for/4-for-even/solution.md index e8e66bb47..92a284fc0 100644 --- a/1-js/02-first-steps/13-while-for/4-for-even/solution.md +++ b/1-js/02-first-steps/13-while-for/4-for-even/solution.md @@ -1,5 +1,3 @@ - - ```js run demo for (let i = 2; i <= 10; i++) { if (i % 2 == 0) { @@ -8,4 +6,4 @@ for (let i = 2; i <= 10; i++) { } ``` -We use the "modulo" operator `%` to get the remainder and check for the evenness here. +Folosim operatorul "modulo" `%` pentru a afla restul împărțirii și astfel a verifica paritatea. diff --git a/1-js/02-first-steps/13-while-for/4-for-even/task.md b/1-js/02-first-steps/13-while-for/4-for-even/task.md index ff34e7e40..ad17de46f 100644 --- a/1-js/02-first-steps/13-while-for/4-for-even/task.md +++ b/1-js/02-first-steps/13-while-for/4-for-even/task.md @@ -2,8 +2,8 @@ importance: 5 --- -# Output even numbers in the loop +# Afișează numerele pare în buclă -Use the `for` loop to output even numbers from `2` to `10`. +Folosește bucla `for` pentru a afișa numele pare între 2 și 10 [demo] diff --git a/1-js/02-first-steps/13-while-for/5-replace-for-while/solution.md b/1-js/02-first-steps/13-while-for/5-replace-for-while/solution.md index 612cf559c..07aecf1ed 100644 --- a/1-js/02-first-steps/13-while-for/5-replace-for-while/solution.md +++ b/1-js/02-first-steps/13-while-for/5-replace-for-while/solution.md @@ -1,10 +1,7 @@ - - ```js run let i = 0; while (i < 3) { - alert( `number ${i}!` ); + alert( `numărul ${i}!` ); i++; } ``` - diff --git a/1-js/02-first-steps/13-while-for/5-replace-for-while/task.md b/1-js/02-first-steps/13-while-for/5-replace-for-while/task.md index 0c69d9c2d..8917f851c 100644 --- a/1-js/02-first-steps/13-while-for/5-replace-for-while/task.md +++ b/1-js/02-first-steps/13-while-for/5-replace-for-while/task.md @@ -2,13 +2,12 @@ importance: 5 --- -# Replace "for" with "while" +# Înlocuiește "for" cu "while" -Rewrite the code changing the `for` loop to `while` without altering its behavior (the output should stay same). +Rescrie codul schimbând bucla `for` cu `while` fără să schimbi comportamentul codului (ceea ce se afișează ar trebui să rămână neschimbat). ```js run for (let i = 0; i < 3; i++) { - alert( `number ${i}!` ); + alert( `numărul ${i}!` ); } ``` - diff --git a/1-js/02-first-steps/13-while-for/6-repeat-until-correct/solution.md b/1-js/02-first-steps/13-while-for/6-repeat-until-correct/solution.md index c7de5f09b..7623c7b1b 100644 --- a/1-js/02-first-steps/13-while-for/6-repeat-until-correct/solution.md +++ b/1-js/02-first-steps/13-while-for/6-repeat-until-correct/solution.md @@ -1,15 +1,14 @@ - ```js run demo let num; do { - num = prompt("Enter a number greater than 100?", 0); + num = prompt("Introdu un număr mai mare ca 100?", 0); } while (num <= 100 && num); ``` -The loop `do..while` repeats while both checks are truthy: +Bucla `do..while` se repetă până amândouă verificările sunt truthy: -1. The check for `num <= 100` -- that is, the entered value is still not greater than `100`. -2. The check `&& num` is false when `num` is `null` or an empty string. Then the `while` loop stops too. +1. Verificarea ca `num <= 100` -- adică, valoarea introdusă încă nu e mai mare ca `100` +2. Verificarea `&& num` e falsă când `num` e fie `null` fie un string gol. Atunci bucla `while` se oprește și ea. -P.S. If `num` is `null` then `num <= 100` is `true`, so without the 2nd check the loop wouldn't stop if the user clicks CANCEL. Both checks are required. +P.S. Dacă `num` e `null` atunci `num <= 100` e `true`, așa că fără a 2-a verificarea bucla nu s-ar mai putea opri decât dacă utilizatorul apasă Anulează. Ambele verificări sunt obligatorii. diff --git a/1-js/02-first-steps/13-while-for/6-repeat-until-correct/task.md b/1-js/02-first-steps/13-while-for/6-repeat-until-correct/task.md index 0788ee76e..142bb949a 100644 --- a/1-js/02-first-steps/13-while-for/6-repeat-until-correct/task.md +++ b/1-js/02-first-steps/13-while-for/6-repeat-until-correct/task.md @@ -2,12 +2,10 @@ importance: 5 --- -# Repeat until the input is correct +# Repetă până numărul introdus e corect -Write a loop which prompts for a number greater than `100`. If the visitor enters another number -- ask them to input again. +Scrie o buclă care să ceară utilizatorului un număr mai mare decât `100`. Dacă utilizatorul introduce alt număr -- cere-i să încerce din nou. -The loop must ask for a number until either the visitor enters a number greater than `100` or cancels the input/enters an empty line. - -Here we can assume that the visitor only inputs numbers. There's no need to implement a special handling for a non-numeric input in this task. +Bucla trebuie să ceară un număr fie până vizitatorul introduce un număr mai mare decât `100` fie anulează introducerea sau introduce un string gol. [demo] diff --git a/1-js/02-first-steps/13-while-for/7-list-primes/solution.md b/1-js/02-first-steps/13-while-for/7-list-primes/solution.md index b4b64b6fa..9d115685d 100644 --- a/1-js/02-first-steps/13-while-for/7-list-primes/solution.md +++ b/1-js/02-first-steps/13-while-for/7-list-primes/solution.md @@ -1,29 +1,29 @@ -There are many algorithms for this task. +Există mulți algoritmi pentru aceast exercițiu. -Let's use a nested loop: +Hai să folosim o buclă imbricată (nested loop): ```js -For each i in the interval { - check if i has a divisor from 1..i - if yes => the value is not a prime - if no => the value is a prime, show it +Pentru fiecare i din interval { + verifică dacă i are un divizor de la 1 la i + dacă da => numărul nu este prim + dacă nu => numărul este prim, afișează-l } ``` -The code using a label: +Codul folosind o etichetă: ```js run let n = 10; -nextPrime: -for (let i = 2; i <= n; i++) { // for each i... +următorulNrPrim: +for (let i = 2; i <= n; i++) { // pentru fiecare i... - for (let j = 2; j < i; j++) { // look for a divisor.. - if (i % j == 0) continue nextPrime; // not a prime, go next i + for (let j = 2; j < i; j++) { // caută un divizor.. + if (i % j == 0) continue următorulNrPrim; // nu e prim, treci la următorul i } - alert( i ); // a prime + alert( i ); // e prim } ``` -There's a lot of space to optimize it. For instance, we could look for the divisors from `2` to square root of `i`. But anyway, if we want to be really efficient for large intervals, we need to change the approach and rely on advanced maths and complex algorithms like [Quadratic sieve](https://en.wikipedia.org/wiki/Quadratic_sieve), [General number field sieve](https://en.wikipedia.org/wiki/General_number_field_sieve) etc. +Aici există foarte multe oportunități de optimizare. De exemplu, am putea căuta divizorii de la `2` la radical din `i`. În orice caz, dacă vrem să fim extrem de eficienți pentru intervale mari, trebuie să schimbăm abordarea și să ne bazăm pe matematică avansată și algoritmi complecși precum [Quadratic sieve](https://en.wikipedia.org/wiki/Quadratic_sieve), [General number field sieve](https://en.wikipedia.org/wiki/General_number_field_sieve), etc. diff --git a/1-js/02-first-steps/13-while-for/7-list-primes/task.md b/1-js/02-first-steps/13-while-for/7-list-primes/task.md index 6344b9f6f..7a7702ce5 100644 --- a/1-js/02-first-steps/13-while-for/7-list-primes/task.md +++ b/1-js/02-first-steps/13-while-for/7-list-primes/task.md @@ -2,16 +2,14 @@ importance: 3 --- -# Output prime numbers +# Afișează numere prime -An integer number greater than `1` is called a [prime](https://en.wikipedia.org/wiki/Prime_number) if it cannot be divided without a remainder by anything except `1` and itself. +Un număr de tip întreg mai mare decât `1` se numește [prim](https://ro.wikipedia.org/wiki/Num%C4%83r_prim) dacă nu se poate împărți fără rest cu nimic în afară de 1 și el însuși. -In other words, `n > 1` is a prime if it can't be evenly divided by anything except `1` and `n`. +Cu alte cuvinte, `n > 1` este prim dacă nu se poate împărți exact cu nimic în afară de `1` și `n`. -For example, `5` is a prime, because it cannot be divided without a remainder by `2`, `3` and `4`. +**Scrie codul care afișează numerele prime în intervalul de la 2 la `n`.** -**Write the code which outputs prime numbers in the interval from `2` to `n`.** +Pentru `n = 10` rezultatul va fi `2,3,5,7`. -For `n = 10` the result will be `2,3,5,7`. - -P.S. The code should work for any `n`, not be hard-tuned for any fixed value. +P.S. Codul ar trebui să funcționeze pentru orice `n`, nu să fie scris pentru o anume valoare. diff --git a/1-js/02-first-steps/13-while-for/article.md b/1-js/02-first-steps/13-while-for/article.md index a7a211569..d315bdc8d 100644 --- a/1-js/02-first-steps/13-while-for/article.md +++ b/1-js/02-first-steps/13-while-for/article.md @@ -1,54 +1,54 @@ -# Loops: while and for +# Bucle: while și for -We often need to repeat actions. +De multe ori avem nevoie să facem o acțiune repetată. -For example, outputting goods from a list one after another or just running the same code for each number from 1 to 10. +De exemplu, afișarea elementelor dintr-o listă unul după altul sau rularea aceluiași cod pentru fiecare număr de la 1 la 10. -*Loops* are a way to repeat the same code multiple times. +*Buclele* sunt o soluție pentru a repeta același cod de mai multe ori. -## The "while" loop +## Bucla "while" -The `while` loop has the following syntax: +Bucla `while` are următoarea sintaxă: ```js -while (condition) { - // code - // so-called "loop body" +while (condiția) { + // codul + // așa-numitul "corp al buclei" } ``` -While the `condition` is truthy, the `code` from the loop body is executed. +Atâta timp cât `condiția` e truthy, `codul` din corpul buclei este excutat. -For instance, the loop below outputs `i` while `i < 3`: +De exemplu, bucla de mai jos afișează `i` cât timp `i < 3`: ```js run let i = 0; -while (i < 3) { // shows 0, then 1, then 2 +while (i < 3) { // afișează 0, apoi 1, apoi 2 alert( i ); i++; } ``` -A single execution of the loop body is called *an iteration*. The loop in the example above makes three iterations. +O singură execuție a corpului buclei se numește *o iterație*. Bucla din exemplul de mai sus face trei iterații. -If `i++` was missing from the example above, the loop would repeat (in theory) forever. In practice, the browser provides ways to stop such loops, and in server-side JavaScript, we can kill the process. +Dacă `i++` lipsea din exemplul de mai sus, bucla s-ar repeta (în teorie) pentru totdeauna. În practică, browserul oferă moduri de a opri astfel de bucle, iar în codul Javascript rulat pe server, putem opri procesul. -Any expression or variable can be a loop condition, not just comparisons: the condition is evaluated and converted to a boolean by `while`. +Orice expresie sau variabilă poate fi o condiție a unei bucle, nu doar comparațiile: condiția e evaluată și transformată într-un boolean de către `while`. -For instance, a shorter way to write `while (i != 0)` is `while (i)`: +De exemplu, putem scrie mai scurt `while (i != 0)` ca `while (i)`: ```js run let i = 3; *!* -while (i) { // when i becomes 0, the condition becomes falsy, and the loop stops +while (i) { // atunci când i devine 0, condiția devine falsy, iar bucla se oprește */!* alert( i ); i--; } ``` -````smart header="Curly braces are not required for a single-line body" -If the loop body has a single statement, we can omit the curly braces `{…}`: +````smart header="Acoladele nu sunt necesare pentru un corp care conține o singură linie de cod" +Dacă corpul buclei are o singură linie de cod, putem omite acoladele `{…}`: ```js run let i = 3; @@ -58,21 +58,21 @@ while (i) alert(i--); ``` ```` -## The "do..while" loop +## Bucla "do...while" -The condition check can be moved *below* the loop body using the `do..while` syntax: +Verificarea condiției poate fi mutată *sub* corpul funcției folosind sintaxa `do...while`: ```js do { - // loop body -} while (condition); + // corpul buclei +} while (condția); ``` -The loop will first execute the body, then check the condition, and, while it's truthy, execute it again and again. +Bucla va rula mai întâi corpul, apoi va verifica condiția, și, cât timp aceasta e truthy, o va executa iar și iar. -For example: +De exemplu: -```js run +```js let i = 0; do { alert( i ); @@ -80,111 +80,110 @@ do { } while (i < 3); ``` -This form of syntax should only be used when you want the body of the loop to execute **at least once** regardless of the condition being truthy. Usually, the other form is preferred: `while(…) {…}`. +Acest tip de sintaxă ar trebui folosit atunci când vrei ca corpul buclei să se execute **cel puțin o dată** indiferent dacă condiția e truthy sau nu. De obicei, se preferă cealaltă formă: `while(...) {...}` -## The "for" loop +## Bucla "for" -The `for` loop is more complex, but it's also the most commonly used loop. +Bucla `for` e mai complexă, dar totodată e cea mai folosită buclă. -It looks like this: +Arată cam așa: ```js -for (begin; condition; step) { - // ... loop body ... +for (inițializator; condiție; pas) { + // ... corpul buclei ... } ``` -Let's learn the meaning of these parts by example. The loop below runs `alert(i)` for `i` from `0` up to (but not including) `3`: +Hai să înțelegem ce înseamnă toate aceste părți printr-un exemplu. Bucla de mai jos rulează `alert(i)` pentru `i` de la `0` până la (dar nu inclusiv) `3`: ```js run -for (let i = 0; i < 3; i++) { // shows 0, then 1, then 2 +for (let i = 0; i < 3; i++) { // afișează 0, apoi 1, apoi 2 alert(i); } ``` -Let's examine the `for` statement part-by-part: +Hai să analizăm fiecare parte a condiției buclei `for`: -| part | | | -|-------|----------|----------------------------------------------------------------------------| -| begin | `let i = 0` | Executes once upon entering the loop. | -| condition | `i < 3`| Checked before every loop iteration. If false, the loop stops. | -| body | `alert(i)`| Runs again and again while the condition is truthy. | -| step| `i++` | Executes after the body on each iteration. | +| parte | | | +| -------------- | ------------- | --------------------------------------------------------------------------------------- | +| inițializator | `let i = 0` | Se execută o dată la începutul buclei. | +| condiția | `i < 3` | Se verifică înainte de fiecare iterație a buclei. Dacă e falsă, bucla se oprește. | +| corpul | `alert(i)` | Rulează iar și iar cât timp condiția e adevărată. | +| pas | `i++` | Rulează după corpul buclei la fiecare iterație. | -The general loop algorithm works like this: +În general, algoritmul buclei funcționează cam așa: ``` -Run begin -→ (if condition → run body and run step) -→ (if condition → run body and run step) -→ (if condition → run body and run step) +Rulează inițializatorul +→ (dacă condiția e adevărată → rulează corpul buclei și rulează pasul) +→ (dacă condiția e adevărată → rulează corpul buclei și rulează pasul) +→ (dacă condiția e adevărată → rulează corpul buclei și rulează pasul) → ... ``` -That is, `begin` executes once, and then it iterates: after each `condition` test, `body` and `step` are executed. +Adică, inițializatorul se execută o dată, iar apoi este iterat: după fiecare test al `condiție`, `corpul` și `pas` sunt rulate. -If you are new to loops, it could help to go back to the example and reproduce how it runs step-by-step on a piece of paper. +Dacă ești nou pe subiectul bucle, te-ar putea ajuta să te întorci la exemplul de mai sus și să reproduci rularea lui pas cu pas pe o coală de hârtie. -Here's exactly what happens in our case: +Aici poți vedea mai exact ce se întâmplă în cazul nostru: ```js // for (let i = 0; i < 3; i++) alert(i) -// run begin +// rulează inițializatorul let i = 0 -// if condition → run body and run step +// dacă condiția e adevărată → rulează corpul buclei și rulează pasul if (i < 3) { alert(i); i++ } -// if condition → run body and run step +// dacă condiția e adevărată → rulează corpul buclei și rulează pasul if (i < 3) { alert(i); i++ } -// if condition → run body and run step +// dacă condiția e adevărată → rulează corpul buclei și rulează pasul if (i < 3) { alert(i); i++ } -// ...finish, because now i == 3 +// ...sfârșit, deoarece acum i == 3 ``` -````smart header="Inline variable declaration" -Here, the "counter" variable `i` is declared right in the loop. This is called an "inline" variable declaration. Such variables are visible only inside the loop. +````smart header="Declararea de variabile inline" +Aici, variabila "contor" `i` este declarată direct în buclă. Asta se numește o declarare de varibilă "inline". Astfel de variabile sunt vizibile numai în interiorul buclei. ```js run for (*!*let*/!* i = 0; i < 3; i++) { alert(i); // 0, 1, 2 } -alert(i); // error, no such variable +alert(i); // eroare, variabila nu există ``` -Instead of defining a variable, we could use an existing one: +În loc să declarăm o variabilă, putem folosi una existentă ```js run let i = 0; -for (i = 0; i < 3; i++) { // use an existing variable +for (i = 0; i < 3; i++) { // folosim o variabilă existentă alert(i); // 0, 1, 2 } -alert(i); // 3, visible, because declared outside of the loop +alert(i); // 3, vizibilă, deoarece a fost declarată în afara buclei de această dată ``` ```` +### Omiterea unor părți -### Skipping parts +Orice parte a buclei `for` poate fi omisă. -Any part of `for` can be skipped. +De exemplu, putem omite `inițializator` dacă nu avem nevoie să facem nimic la începutul buclei. -For example, we can omit `begin` if we don't need to do anything at the loop start. - -Like here: +Precum aici: ```js run -let i = 0; // we have i already declared and assigned +let i = 0; // deja îl avem pe i declarat și inițializat -for (; i < 3; i++) { // no need for "begin" +for (; i < 3; i++) { // nu avem nevoie de "inițializator" alert( i ); // 0, 1, 2 } ``` -We can also remove the `step` part: +Putem omite de asemenea și `pas`: -```js run +```js let i = 0; for (; i < 3;) { @@ -192,32 +191,32 @@ for (; i < 3;) { } ``` -This makes the loop identical to `while (i < 3)`. +Asta face ca bucla să fie identică cu `while(i < 3)`. -We can actually remove everything, creating an infinite loop: +Putem chiar să omitem totul, creeând o buclă infintă. ```js for (;;) { - // repeats without limits + // se repetă fără limită } ``` -Please note that the two `for` semicolons `;` must be present. Otherwise, there would be a syntax error. +Te rugăm să reții că cele două "punct și virgulă" `;` din bucla `for` trebuie să fie prezente. Altminteri, ar apărea un syntax error. -## Breaking the loop +## Întreruperea buclei -Normally, a loop exits when its condition becomes falsy. +În mod normal, o buclă se întrerupe atunci când condiția sa devine falsy. -But we can force the exit at any time using the special `break` directive. +Dar putem forța întreruperea în orice moment prin folosirea instrucțiunii `break`. -For example, the loop below asks the user for a series of numbers, "breaking" when no number is entered: +De exemplu, bucla de mai jos îi cere utilizatorului o serie de numere, "întrerupându-se" atunci când nici-un număr nu a fost furnizat: ```js run let sum = 0; while (true) { - let value = +prompt("Enter a number", ''); + let value = +prompt("Introdu un număr", ''); *!* if (!value) break; // (*) @@ -226,35 +225,35 @@ while (true) { sum += value; } -alert( 'Sum: ' + sum ); +alert( 'Sumă: ' + sum ); ``` -The `break` directive is activated at the line `(*)` if the user enters an empty line or cancels the input. It stops the loop immediately, passing control to the first line after the loop. Namely, `alert`. +Instrucțiunea `break` e activată de linia `{*}` dacă utilizatorul nu introduce nimic sau dacă anulează introducerea. Bucla se întrerupe imediat și este rulată ultima linie de cod de după buclă. -The combination "infinite loop + `break` as needed" is great for situations when a loop's condition must be checked not in the beginning or end of the loop, but in the middle or even in several places of its body. +Combinația "buclă infinită + `break` în funcție de necesități" e excelentă în situații când condiția unei bucle nu trebuie verificată de la început sau la final, ci în mijlocul sau chiar în mai multe locuri din corpul buclei. -## Continue to the next iteration [#continue] +## Continuă cu următoarea iterație [#continue] -The `continue` directive is a "lighter version" of `break`. It doesn't stop the whole loop. Instead, it stops the current iteration and forces the loop to start a new one (if the condition allows). +Instrucțiunea `continue` e o "versiune mai blândă" a lui `break`. Nu oprește toată bucla. În schimb, oprește iterația actuală și forțează bucla să înceapă una nouă (dacă condiția permite aceasta). -We can use it if we're done with the current iteration and would like to move on to the next one. +O putem folosi dacă am terminat cu iterația curentă și vrem să trecem la următoarea. -The loop below uses `continue` to output only odd values: +Bucla de mai jos folosește `continue` ca să afișeze numai valorile impare: ```js run no-beautify for (let i = 0; i < 10; i++) { - // if true, skip the remaining part of the body + // dacă e adevărat, treci peste restul corpului buclei *!*if (i % 2 == 0) continue;*/!* - alert(i); // 1, then 3, 5, 7, 9 + alert(i); // 1, apoi 3, 5, 7, 9 } ``` -For even values of `i`, the `continue` directive stops executing the body and passes control to the next iteration of `for` (with the next number). So the `alert` is only called for odd values. +Pentru valorile pare ale lui `i`, instrucțiunea `continue` oprește executarea corpului și rulează următoarea iterație a lui `for` (cu următorul număr). Astfel funcția `alert` e apelată numai pentru valorile impare. -````smart header="The `continue` directive helps decrease nesting" -A loop that shows odd values could look like this: +````smart header="Instrucțiunea `continue` ajută la diminuarea nesting-ului" +O buclă care afișează valorile impare ar putea arăta așa: ```js run for (let i = 0; i < 10; i++) { @@ -266,15 +265,14 @@ for (let i = 0; i < 10; i++) { } ``` -From a technical point of view, this is identical to the example above. Surely, we can just wrap the code in an `if` block instead of using `continue`. +Dintr-un punct de vedere tehnic, aceasta este identică cu exemplul de mai sus. Desigur, putem și să încadrăm codul de mai sus într-un `if` block în loc să folosim `continue`. -But as a side-effect, this created one more level of nesting (the `alert` call inside the curly braces). If the code inside of `if` is longer than a few lines, that may decrease the overall readability. ```` -````warn header="No `break/continue` to the right side of '?'" -Please note that syntax constructs that are not expressions cannot be used with the ternary operator `?`. In particular, directives such as `break/continue` aren't allowed there. +````warn header="Fără `break/continue` în dreapta a '?'" +Vă rugăm să rețineți că construcțiile de sintaxă care nu sunt expresii nu pot fi folosite cu operatorul ternar `?`. În particular, instrucțiuni precum `break/continue` nu sunt permise acolo. -For example, if we take this code: +De exemplu, dat fiind acest cod: ```js if (i > 5) { @@ -284,114 +282,115 @@ if (i > 5) { } ``` -...and rewrite it using a question mark: +...rescriindu-l cu un semn de întrebare: ```js no-beautify -(i > 5) ? alert(i) : *!*continue*/!*; // continue isn't allowed here +(i > 5) ? alert(i) : *!*continue*/!*; // continue nu e permis aici ``` -...it stops working: there's a syntax error. +...nu mai funcționează: apare un syntax error. -This is just another reason not to use the question mark operator `?` instead of `if`. +Acesta e un alt motiv de a nu folosi operatorul `?` în favoarea lui `if`. ```` -## Labels for break/continue +## Denumiri pentru break/continue -Sometimes we need to break out from multiple nested loops at once. +Uneori avem nevoie să întrerupem mai multe bucle odată. -For example, in the code below we loop over `i` and `j`, prompting for the coordinates `(i, j)` from `(0,0)` to `(2,2)`: +De exemplu, în codul de mai jos iterăm pentru `i` și `j`, afișând coordonatele `(i, j)` de la `(0, 0)` la `(2, 2)`: ```js run no-beautify for (let i = 0; i < 3; i++) { for (let j = 0; j < 3; j++) { - let input = prompt(`Value at coords (${i},${j})`, ''); + let input = prompt(`Valoare la coordonatele (${i},${j})`, ''); - // what if we want to exit from here to Done (below)? + // ce-ar fi dacă am vrea să întrerupem buclele și să sărim direct la Gata (dedesubt) } } -alert('Done!'); +alert('Gata!'); ``` -We need a way to stop the process if the user cancels the input. +Avem nevoie de o cale de a opri procesul dacă utilizatorul anulează introducerea de text. + +Banalul `break` pus după `input` ar întrerupe doar bucla din interior. Asta nu e suficient - etichetelor, veniți și salvați-ne! -The ordinary `break` after `input` would only break the inner loop. That's not sufficient -- labels, come to the rescue! +O *etichetă* este un indentificator urmat de două puncte înainte de o buclă: -A *label* is an identifier with a colon before a loop: ```js labelName: for (...) { ... } ``` -The `break ` statement in the loop below breaks out to the label: +Expresia `break ` din bucla de mai jos întrerupe bucla etichetată: -```js run no-beautify +```js run no beautify *!*outer:*/!* for (let i = 0; i < 3; i++) { for (let j = 0; j < 3; j++) { - let input = prompt(`Value at coords (${i},${j})`, ''); + let input = prompt(`Valoare la coordonatele (${i},${j})`, ''); - // if an empty string or canceled, then break out of both loops + // dacă e un string gol sau e anulat, atunci întrerupe if (!input) *!*break outer*/!*; // (*) - // do something with the value... + // fă ceva cu valorea... } } -alert('Done!'); +alert('Gata!'); ``` -In the code above, `break outer` looks upwards for the label named `outer` and breaks out of that loop. +În codul de mai sus, `break outer` caută eticheta cu numele `outer` și întreupe acea buclă. -So the control goes straight from `(*)` to `alert('Done!')`. +Deci execuția codului sare de la `(*)` la `alert('Gata!')`. -We can also move the label onto a separate line: +De asemenea, putem să mutăm eticheta pe o linie separată: ```js no-beautify -outer: +exterior: for (let i = 0; i < 3; i++) { ... } ``` -The `continue` directive can also be used with a label. In this case, code execution jumps to the next iteration of the labeled loop. +Și instrucțiunea `continue` poate să fie folosită cu o etichetă. În acest caz, execuția codului sare la următoarea iterație a buclei etichetate. -````warn header="Labels do not allow to \"jump\" anywhere" -Labels do not allow us to jump into an arbitrary place in the code. +````warn header="Etichetele nu ne permit să \"sărim\" oriune" +Etichetele nu ne permit să sărim la locuri din cod alese arbitrar. -For example, it is impossible to do this: +De exemplu, e imposibil să facem asta: ```js -break label; // jump to the label below (doesn't work) +break etichetă; // sare la eticheta de dedesubt (nu funcționează) -label: for (...) +etichetă: for (...) ``` -A `break` directive must be inside a code block. Technically, any labelled code block will do, e.g.: +Instrucțiunea `break` trebuie să fie în interiorul unui code block. Practic, orice code block ar funcționa, de exemplu: ```js -label: { +etichetă: { // ... - break label; // works + break label; // funcționează // ... } ``` -...Although, 99.9% of the time `break` is used inside loops, as we've seen in the examples above. +...Cu toatea acestea, în 99.9% din cazuri `break` este folosit în interiorul buclelor, precum am văzut în exemplele de mai sus. -A `continue` is only possible from inside a loop. +`Continue` poate fi folosit numai în interiorul unei bucle. ```` -## Summary +## Rezumat -We covered 3 types of loops: +Am vorbit despre 3 tipuri de bucle: -- `while` -- The condition is checked before each iteration. -- `do..while` -- The condition is checked after each iteration. -- `for (;;)` -- The condition is checked before each iteration, additional settings available. +- `while` -- Condiția este verificată înainte de fiecare iterație. +- `do..while` -- Condiția este verificată după fiecare iterație. +- `for (;;)` -- Condiția este verificată înainte de fiecare iterație, avem și alte setări disponibile. -To make an "infinite" loop, usually the `while(true)` construct is used. Such a loop, just like any other, can be stopped with the `break` directive. +Pentru a face o buclă "infinită", de obicei este folosită secvența `while(true)`. O astfel de buclă, la fel ca oricare alta, poate fi oprită cu instrucțiunea `break`. -If we don't want to do anything in the current iteration and would like to forward to the next one, we can use the `continue` directive. +Dacă nu vrem să facem nimic în iterația curentă și am vrea să trecem la următoarea, putem folosi instrucțiunea `continue`. -`break/continue` support labels before the loop. A label is the only way for `break/continue` to escape a nested loop to go to an outer one. +`break/continue` admit etichete înainte de buclă. O etichetă este singurul mod pentru `break/continue` să întrerupă o buclă imbricată și să treacă la una exterioară.