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

chapter 3) Using conditional operators

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

      const result = (number >= 0) ? 'over 0' : 'under 0'
      alert(result)
    </script>
</head>
<body>

</body>
</html>

### Script Breakdown

- `const input = prompt('Number : ', '')`: This line displays a prompt dialog box asking the user to enter a number. The second parameter of `prompt` is the default text, which is set to an empty string here. The user's input is stored in the `input` variable.

- `const number = Number(input)`: The user's input is converted to a number using the `Number` constructor. If the input cannot be converted into a number (e.g., if the user enters non-numeric characters), `number` will be `NaN` (Not-a-Number).

- `const result = (number >= 0) ? 'over 0' : 'under 0'`: This line uses the ternary operator to evaluate `number`. The condition `number >= 0` checks if the number is greater than or equal to 0.
  - If `true`, the result is `'over 0'`, indicating that the number is either positive or zero.
  - If `false`, the result is `'under 0'`, indicating that the number is negative.

- `alert(result)`: Finally, an alert dialog box displays the result of the evaluation to the user.

### Execution Flow

1. When the document loads in a web browser, it immediately prompts the user to enter a number.
2. After entering a number (or any other input), the script evaluates whether the input, when converted to a number, is greater than or equal to 0.
3. Based on the evaluation, an alert box is shown displaying either `'over 0'` for numbers greater than or equal to 0 (including positive numbers and zero) or `'under 0'` for numbers less than 0 (negative numbers).

### Considerations

- If the user inputs something that isn't a number (e.g., letters or symbols), the `Number` constructor will result in `NaN`. The condition `number >= 0` will evaluate to `false` in this case, and the alert will display `'under 0'`. This might be slightly misleading since `NaN` isn't less than 0; it's just not a number. If handling non-numeric input more explicitly is desired, additional checks for `NaN` can be introduced.
- This script is executed immediately as the page loads. For more complex applications or improved user experience, it's common to trigger such interactions with an event, such as clicking a button.

728x90
반응형
LIST