Apply your knowledge to build something amazing!
:information_source: Project Overview Difficulty Level: Beginner
Estimated Time: 45-60 minutes
Skills Practiced:
- Variables and data types
- While loops and control flow
- User input validation
- Mathematical calculations
- Conditional statements (if/else)
- JavaScript methods (.toFixed(), isNaN())
graph LR
A[Phase 1: Setup] --> B[Phase 2: Input Collection]
B --> C[Phase 3: Validation]
C --> D[Phase 4: Calculation]
D --> E[Phase 5: Display Results]
E --> F[Phase 6: Advanced Features]
style A fill:#e1f5e1
style B fill:#fff3cd
style C fill:#f8d7da
style D fill:#d1ecf1
style E fill:#d4edda
style F fill:#e2e3e5
What you'll do: Open the project and familiarize yourself with the interface
DO NOT DELETE the existing files in the template:
ONLY EDIT the necessary files.
Let's create a BMI calculator using all the knowledge we've learnt from chapter 1 to 5.
The idea is that your BMI calculator will validate the input and keep looping until the correct input is given.
:bulb: What is BMI? BMI (Body Mass Index) is a simple calculation that helps determine if someone's weight is healthy for their height. The formula is:
ini
BMI = weight (kg) / (height (m))²
Before diving into coding, make sure you have:
script.js
file where you'll write your codeGreat job setting up! Now let's start building! :rocket:
You must follow the following instructions:
weightKG
and heightCM
, giving each variable a default value of 0.// Start your code here
let weightKG = 0;
let heightCM = 0;
:bulb: Best Practice Always initialize your variables! This prevents unexpected errors and makes your code more predictable.
weightKG
prompt.
weightKG
is equal to 0, prompt an input for weightKG
.:warning: Common Pitfall Remember that
prompt()
returns a string! You'll need to convert it to a number usingNumber()
orparseFloat()
.
weightKG
in step 2, create a while loop for the heightCM
prompt.
heightCM
is equal to 0, prompt an input for heightCM
.Before proceeding, test your code:
heightMeter
// Hint: To convert cm to meters, divide by 100
let heightMeter = heightCM / 100;
:bulb: Math in JavaScript To square a number in JavaScript, you can use:
Math.pow(heightMeter, 2)
- Or simply:
heightMeter * heightMeter
.toFixed()
method. Check this page for more information: https://www.w3schools.com/jsref/jsref_tofixed.asp// Example of using toFixed()
let bmi = 23.456789;
let roundedBMI = bmi.toFixed(1); // Result: "23.5"
This is the weight category:
:information_source: BMI Categories
- Underweight: ``BMI < 18.5``
- Normal weight: BMI 18.5 - 24.9
- Overweight: ``BMI >= 25``
According to the BMI result, alert the user with this:
// Use if-else statements to check BMI ranges
if (BMI < 18.5) {
alert("Your BMI is " + BMI + ". You're underweight." );
} else if (BMI >= 18.5 && BMI < 25) {
alert("Your BMI is " + BMI + ". You've a normal weight." );
} else {
alert("Your BMI is " + BMI + ". You're overweight." );
}
:warning: Important Note The code above shows JavaScript syntax, not Python. Make sure you're using the correct language!
Congratulations! Your basic BMI calculator should now:
If you have done it correctly, it should look like this:
Assuming your weight is 60kg and your height is 170 cm.
If the input is 0 for weight and height, it should look like this:
:bulb: Testing Tip Try these test cases to make sure your calculator works correctly:
- Weight: 60kg, Height: 170cm -> BMI should be 20.8 (Normal)
- Weight: 50kg, Height: 170cm -> BMI should be 17.3 (Underweight)
- Weight: 80kg, Height: 170cm -> BMI should be 27.7 (Overweight)
Let's make the validation even better. Modify your validation conditions in your while loop so that it also cannot accept negative numbers and it cannot accept inputs that are not a number.
:warning: Common Validation Mistakes Students often forget to check for:
- Negative numbers (weight: -50)
- Text input ("hello" instead of a number)
- Empty input (just pressing Enter)
- Very large unrealistic numbers
isNaN()
function.// Example of improved validation
while (weightKG <= 0 || isNaN(weightKG)) {
weightKG = Number(prompt("Enter your weight in kg:"));
if (weightKG <= 0 || isNaN(weightKG)) {
alert("Invalid weight. Please enter a positive number.");
}
}
If your calculator isn't working as expected, try these debugging strategies:
Use console.log() to check values:
console.log("Weight entered:", weightKG);
console.log("Height entered:", heightCM);
console.log("Calculated BMI:", BMI);
Check the browser console (F12) for error messages
Test edge cases:
:bulb: Pro Debugging Tip Add temporary alert messages to see what values your variables hold at different points in your code. Remove them once everything works!
Your enhanced BMI calculator should now:
Ready to take your BMI calculator to the next level? Try these challenges:
Add an option for users to input weight in pounds and height in inches:
Store multiple BMI calculations in an array and display them at the end:
let bmiHistory = [];
// Add each calculation to the array
// Display all calculations when user is done
Based on the BMI category, provide specific health tips:
Create a simple text-based visualization of where the user's BMI falls:
Underweight | Normal | Overweight
| [X] |
:bulb: Challenge Approach Start with Challenge 1 and work your way up. Each challenge builds on the skills from the previous one!
Code Review: https://youtu.be/vIxYKE3OQDA
When you have completed your "BMI Calculator" project, submit it using the link below:
Make sure to test your webpage before submitting to ensure all required elements are working properly!
:bulb: Final Checklist Before submitting, ensure your calculator:
- :white_check_mark: Accepts and validates weight input
- :white_check_mark: Accepts and validates height input
- :white_check_mark: Calculates BMI correctly
- :white_check_mark: Shows the correct weight category
- :white_check_mark: Handles invalid inputs gracefully
- :white_check_mark: Works with the advanced validation requirements
You've got this! :muscle: