javascript / beginner
Snippet
Validating Numerical Range Boundaries with Guard Clauses
Guard clauses use conditional statements to return early from a function when input constraints are violated. This pattern eliminates nested conditionals and guarantees that subsequent logic only runs on clean, valid numerical data within the expected range.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<script>let score = 0;let validationMessage = '';function evaluateScore(value) {if (Number.isNaN(value) || value < 0 || value > 100) {validationMessage = 'Score must be a number between 0 and 100.';return;}validationMessage = value >= 50 ? 'Passed exam' : 'Failed exam';}</script><input type="number" bind:value={score} on:input={() => evaluateScore(score)} /><p>{validationMessage}</p>
svelte
Breakdown
1
if (Number.isNaN(value) || value < 0 || value > 100) {
Checks for non-numbers or values outside the permitted range of 0 to 100.
2
return;
Exits the function immediately to prevent execution of downstream grading logic.
3
validationMessage = value >= 50 ? 'Passed exam' : 'Failed exam';
Evaluates the validated score using a ternary conditional operator.