# arr.forEach()

[JS](https://lochiwei.gitbook.io/web/js)⟩ [syntax](https://lochiwei.gitbook.io/web/js/grammar/statement/loop/for/broken-reference) ⟩ [for loops](https://lochiwei.gitbook.io/web/js/grammar/statement/loop/for) ⟩ arr.forEach()

{% hint style="warning" %}

* to <mark style="color:yellow;">**skip**</mark> a case, use <mark style="color:blue;">**return**</mark>.&#x20;
* ⭐️ there's <mark style="color:red;">**no way**</mark> to <mark style="color:blue;">**break**</mark>/<mark style="color:blue;">**continue**</mark> in this method❗️
  {% endhint %}

{% tabs %}
{% tab title="💾 程式" %}
💾 程式：[replit](https://replit.com/@pegasusroe/forEach-continue#index.js)

```javascript
let array = [1, 2, 3, 4, 5];

// ⭐️ skip a case with `return`
array.forEach(n => {
    if (n % 2 !== 0) return;        // ✅ use `return`
    console.log(n);                 // 2, 4
});

// ⭐️ skip cases with `filter()`
array
    .filter(n => n % 2 == 0)        // ✅ use `filter`
    .forEach(n => console.log(n));  // 2, 4aa
```

{% endtab %}

{% tab title="🧨 雷區" %}

* replit：[no break/continue in forEach()](https://replit.com/@pegasusroe/no-continuebreak-in-forEach#index.js)

```javascript
let array = [1, 2, 3, 4, 5];

// ❌ can't use `break` in .forEach()
array.forEach(n => {
    if (n % 2 !== 0) break;    
    //               ^^^^^
    // ⛔ SyntaxError:
    //    "Illegal break statement"
});

// ❌ can't use `continue` in .forEach()
array.forEach(n => {
    if (n % 2 !== 0) continue;    
    //               ^^^^^^^^
    // ⛔ SyntaxError:
    //    "Illegal continue statement: no surrounding iteration statement"
});
```

{% endtab %}

{% tab title="📗 參考" %}

* [ ] [Using Continue in JavaScript forEach()](https://masteringjs.io/tutorials/fundamentals/foreach-continue) - use <mark style="color:red;">**return**</mark> to skip a case
  {% endtab %}

{% tab title="📘 手冊" %}

* Array.prototype.[forEach()](https://developer.mozilla.org/zh-TW/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach)
  {% endtab %}

{% tab title="🚧" %}
{% hint style="warning" %}
to do：

* <mark style="color:blue;">**break**</mark> statement
* <mark style="color:blue;">**continue**</mark> statement
  {% endhint %}
  {% endtab %}
  {% endtabs %}
