본문 바로가기
개념/혼자 공부하는 Javascript

chapter 5) Array methods and arrow functions

by kiseno 2024. 4. 3.
728x90
반응형
SMALL
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script>
        let numbers = [0,1,2,3,4,5,6,7,8,9]
        numbers.filter((value) => value % 2 ===0).map((value => value * value)).forEach((value) => {
            console.log(value)
        })
    </script>
</head>
<body>

</body>
</html>

 

### Initial Array
- The `numbers` array is initialized with integers from `0` to `9`.

### Operations Chain
- **Filter**: `numbers.filter((value) => value % 2 === 0)` filters the array to include only even numbers. The condition `value % 2 === 0` evaluates to `true` for even numbers. The result of this operation is an array of even numbers: `[0, 2, 4, 6, 8]`.
  
- **Map**: `.map((value) => value * value)` takes the array of even numbers and transforms each number by squaring it. The operation `value * value` is applied to each element, resulting in: `[0, 4, 16, 36, 64]`.
  
- **ForEach**: `.forEach((value) => {console.log(value)})` iterates over the array of squared even numbers and logs each value to the console. This method executes the provided function once for each array element.

### Execution Flow
- When the document is loaded in a web browser, the script automatically executes.
- The console will log the squared values of the even numbers from the original array, in this case: `0`, `4`, `16`, `36`, `64`.

### Purpose and Usage
- This script demonstrates the use of `filter`, `map`, and `forEach` methods in JavaScript for array manipulation. These methods are part of the functional programming capabilities in JavaScript, allowing for efficient and expressive data processing.
- The use of arrow functions (`(value) => ...`) makes the code more concise and readable.
- This pattern is commonly used in JavaScript for transforming data, such as when processing datasets or manipulating values for display.

### Output Visibility
- The output from this script (the squared even numbers) will appear in the browser's developer console, which can be accessed typically by pressing F12 or right-clicking on the page and selecting "Inspect" or "Inspect Element", then navigating to the "Console" tab.
- This approach is useful for debugging or displaying information during development, rather than for interacting with users in a production environment.

728x90
반응형
LIST