By the end of this lesson, you will know how to write small checks and test edge cases in your JavaScript code. You will also understand how to improve the reliability of your functions by ensuring they handle unexpected inputs.
Writing small checks involves performing quick tests in our code to verify that everything functions as intended. For example, if you create a program that calculates student grades, you should check how it handles scenarios like scores below zero or above 100. These are known as edge cases, which could lead to errors if they are not properly managed. Therefore, it is essential that we include these checks.
When we write small checks, we ensure our programs can effectively handle various inputs. Not considering edge cases can result in unexpected behavior in our applications. For instance, if a user inputs an invalid score, our program should handle it gracefully rather than crashing or providing erroneous outputs. This is why practicing small checks in coding is crucial for beginner programmers.
File: gradeCheck.js
function checkGrade(grade) {
if (grade < 0 || grade > 100) {
return "Invalid grade! Please enter a value between 0 and 100.";
} else if (grade >= 90) {
return "A";
} else if (grade >= 80) {
return "B";
} else if (grade >= 70) {
return "C";
} else if (grade >= 60) {
return "D";
} else {
return "F";
}
}
console.log(checkGrade(105)); // Invalid grade! Please enter a value between 0 and 100.
console.log(checkGrade(85)); // B
console.log(checkGrade(-10)); // Invalid grade! Please enter a value between 0 and 100.
In this example, we declare a function checkGrade that takes a grade as input. First, we check if the grade is less than 0 or greater than 100. If it is, we return a message saying the grade is invalid. If the grade is valid, we return a letter grade based on its value. The lines with return send our results back to where the function was called. This structure helps to ensure that we are writing small checks throughout our program.
Now, create a function called checkAge that takes an age as input. It should return “You are a minor” if the age is under 18 and “You are an adult” if 18 or older. Therefore, test your function with various ages, including negative numbers and significantly high values. This exercise will help reinforce how to effectively write small checks in your code.
function checkAge(age) {
if (age < 0) {
return "Invalid age! Please enter a valid age.";
} else if (age >= 18) {
return "You are an adult.";
} else {
return "You are a minor.";
}
}
console.log(checkAge(17)); // You are a minor.
console.log(checkAge(18)); // You are an adult.
console.log(checkAge(-5)); // Invalid age! Please enter a valid age.