# 07-2. 배열내장 함수(forEach)

## 배열내장 함수

배열을 다룰 때 알고있으면 너무나 유용한 다양한 내장 함수들에 대하여 알아보겠습니다.

### forEach

**매개변수**\
&#x20;   callback : 각 요소에 대해 실행할 함수. 다음 세 가지 매개변수를 받습니다.\
&#x20;       currentValue : 배열 내 현재 값.\
&#x20;       index: 배열 내 현재 값의 인덱스.\
&#x20;       array:  현재 배열 입니다.

`forEach` 는 가장 쉬운 배열 내장함수입니다. 기존에 우리가 배웠던 for 문을 대체 시킬 수 있습니다. 예를 들어서 다음과 같은 텍스트 배열이 있다고 가정해봅시다.

```javascript
const superheroes = ['아이언맨', '캡틴 아메리카', '토르', '닥터 스트레인지'];
```

만약, 배열 안에 있는 모든 원소들을 모두 출력해야 한다면 for 문을 사용하여 다음과 같이 구현 할 수 있는데요,

```javascript
const superheroes = ['아이언맨', '캡틴 아메리카', '토르', '닥터 스트레인지'];

for (let i = 0; i < superheroes.length; i++) {
  console.log(superheroes[i]);
}
```

```javascript
// 결과)
아이언맨
캡틴 아메리카
토르
닥터 스트레인지
```

배열의 forEach 함수를 사용하면 다음과 같이 구현 할 수 있습니다.

```javascript
const superheroes = ['아이언맨', '캡틴 아메리카', '토르', '닥터 스트레인지'];

// *1) 방법*
var print = function(hero) {
  console.log(hero);
};

superheroes.forEach(print); // 함수형태의 파라미터를 전달하 것을 콜백함수 라고 부릅니다.

// *2) 방법*  1번 방법보다 더 깔끔하게 작성이 가능하다.
superheroes.forEach(function(hero){
  console.log(hero);
});

// *3) 방법*  2번 방법보다 더 깔끔하게 작성이 가능하다.
superheroes.forEach(hero => {
  console.log(hero);
});
```

```javascript
// 결과)
아이언맨
캡틴 아메리카
토르
닥터 스트레인지
```

forEach 함수의 파라미터로는, 각 원소에 대하여 처리하고 싶은 코드를 함수로 넣어줍니다. 이 함수의 파라미터 hero는 각 원소를 가르키게 됩니다.

이렇게 함수형태의 파라미터를 전달하는 것을 콜백함수 라고 부릅니다. 함수를 등록해주면, forEach 가 실행을 해주는 거죠.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://triplexlab.gitbook.io/vanilla-js/basics/07-array/07-2-foreach.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
