Hey there, coding friend!
Welcome to our tutorial on If-Else If Structure in JavaScript! Today, we're going to learn how to use this powerful tool to make decisions in our code. And, we're going to do it in a super practical way - by determining a student's grade based on their exam score!
Step 1: Open your index.js file Open the index.js file in your online IDE and get ready to code!
The Problem: Determine a Student's Grade Imagine you're a teacher, and you want to write a program that determines a student's grade based on their exam score. The grading scale is as follows:
Let's Start Coding!
Create a variable score
and assign it a value, let's say 85. We'll use this value to determine the grade.
let score = 85
If-Else If Structure
Now, let's use an If-Else If Structure to determine the grade based on the score. We'll start with an if
statement to check if the score is 90 or above.
if (score >= 90) { console.log("Grade: A")}
Run the code by clicking the "Run" button. You should see "Grade: A" in the console. But, wait! We need to handle the other grades too.
Adding Else If Statements
Let's add else if
statements to check for the other grades. We'll add conditions for scores between 80-89, 70-79, 60-69, and below 60.
if (score >= 90) { console.log("Grade: A")} else if (score >= 80) { console.log("Grade: B")} else if (score >= 70) { console.log("Grade: C")} else if (score >= 60) { console.log("Grade: D")} else { console.log("Grade: F")}
Run the Code Again!
Click the "Run" button to see the output. You should see "Grade: B" in the console, since our score
is 85.
Experiment Time!
Try changing the score
variable to different values, like 70, 95, or 40, and see how the output changes. This will help you understand how the If-Else If Structure works.
What's Next? In our next tutorial, we'll learn about the Switch Statement, which is another powerful tool for making decisions in our code.
You've made it to the end of this tutorial! Pat yourself on the back, coding friend! You now know how to use If-Else If Structures to make decisions in your code. Keep practicing, and soon you'll be a master coder!
Happy coding!
Tests