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

chapter 3) Using switch conditional statements

by kiseno 2024. 11. 26.
728x90
반응형
SMALL
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script>
        const input = Number(prompt('Number : ', 'Number'))

        switch (input % 2){
            case 0:
                alert('even')
                break
            case 1:
                alert('odd')
                break
            default:
                alert('not number')
                break
        }
    </script>
</head>
<body>

</body>
</html>

### Breakdown of the JavaScript Code

- `const input = Number(prompt('Number : ', 'Number'))`: This line displays a prompt dialog box asking the user to enter a number. The input is then converted to a number type using the `Number` constructor. If the input cannot be converted to a number, the result will be `NaN` (Not-a-Number).
  
- `switch (input % 2)`: The modulo operator (`%`) is used to get the remainder of the division of `input` by `2`. This operation helps determine if the number is even or odd. The result is used in a `switch` statement to match against different cases.
  
  - `case 0`: If `input % 2` equals `0`, the number is even. An alert box with the message `'even'` is displayed.
  
  - `case 1`: If `input % 2` equals `1`, the number is odd. An alert box with the message `'odd'` is displayed.
  
  - `default`: The default case handles situations where the input is not an even or odd number, which includes `NaN` resulting from non-numeric inputs. It displays an alert box with the message `'not number'`.

### Execution Flow

1. When the document is loaded in a web browser, the user is immediately prompted to enter a number.
2. The user's input is converted to a number and evaluated to determine if it is even, odd, or not a number.
3. An alert box is displayed to the user indicating whether the entered number is even, odd, or not a number based on the input's evaluation.

### Considerations

- The use of the `Number` constructor ensures that non-numeric inputs result in `NaN`. The modulo operation with `NaN` will also yield `NaN`, which won't match `case 0` or `case 1` and thus will hit the `default` case.
- This script assumes that the user will input integer values. For floating-point numbers, the result of the modulo operation might not be strictly `0` or `1`, but the `default` case will handle any input that doesn't produce a `0` remainder for being even.
- The script is executed as soon as the page loads, which might not always be the desired behavior in a more complex application. For a more interactive application, this code could be wrapped in a function and called based on a specific event, like clicking a button.

728x90
반응형
LIST