JavaScript If...Else Statements Tutorial

HTML by nature is a linear language. It reads a document line by line from top to bottom and outputs the contents into a browser window following that linear fashion. JavaScript is much more dynamic. Regardless of its place within a document, the DOM can access and modify a document's flow, making it a rebel of all that HTML mark-up and its linear output stands for.

In JavaScript, the If...Else statements challenge the conventional process of how HTML is displayed because it offers an opportunity to create subroutines and therefore, options only limited by the imagination and scope of the JavaScript code.

If...Else Statements and Comparison Operators

The script example provided demonstrates how an If...Else statement with several conditions can return one of many choices. This is based on user-generated inputs.

Code Example
  1. var age=parseInt(prompt("How old are you?",""));
  2. if (age<=4) {
  3. alert("Aw, you are going to start preschool soon!");
  4. } else
  5. if (age<=17) {
  6. alert("How's school these days?");
  7. } else
  8. if (age>=45) {
  9. alert("You should check your superannuation investment fund");
  10. } else
  11. if (age>=30) {
  12. alert("You should consider university");
  13. } else
  14. if (age>=17) {
  15. alert("It's tough getting old");
  16. } else {
  17. alert("You need to enter a number"); }

JavaScript is so extensible as to allow limitless capability. The If...Else statement, along with conditional statements, comparison operators and calls to other functions creates a dynamic engine-room behind the scenes.

This second example prompts for your school grade and displays a suitable message for their performance.

Code Example
  1. var grade=parseInt(prompt("What was your total grade","From 1 to 100"));
  2. if (grade<=40) {
  3. alert("Sorry. You received a fail for this class");
  4. } else
  5. if (grade>=85) {
  6. alert("Congratulations, you received a High Distinction");
  7. } else
  8. if (grade>=70) {
  9. alert("Congratulations, you received a Distinction");
  10. } else
  11. if (grade>=60) {
  12. alert("Congratulations, you received a credit");
  13. } else
  14. if (grade>=41) {
  15. alert("Congratulations, you received a pass");
  16. } else
  17. { alert("You need to enter a number");
  18. }