JavaScript - SPLessons

JavaScript Conditions

Home > Lesson > Chapter 8
SPLessons 5 Steps, 3 Clicks
5 Steps - 3 Clicks

JavaScript Conditions

JavaScript Conditions

shape Description

 JavaScript supports various conditional statements that perform different actions based on a set of conditions. JavaScript executes a block of code based on certain JavaScript Conditions and continues executing till all the conditions are met. There are four decision making statements in JavaScript.

if statement

shape Description

The condition code will be executed only when the given condition is true in JavaScript Conditions, otherwise, the program skips the execution part of that particular block.

shape Syntax

if(condition) { //statements; }

shape Flow Chart

shape Examples

[html] <!Doctype html> <html> <head> <title>Conditional Statements</title> <h2 style="color: grey">Example for if statement</h2> </head> <body> <script type="text/javascript"> var a = 5; if(a < 10) { document.write("GoodMorning"); } </script> </body> </html>[/html] Output

if..else statement

shape Description

if...else code will be executed only when the given condition in the "if" block is true, otherwise it executes the statements of "else" block.

shape Syntax

if(condition) { //statements; } else { //statements; }

shape Flow Chart

shape Examples

[c] <!Doctype html> <html> <head> <title>Conditional Statements</title> <h2 style="color: grey">Example for if...else statement</h2> </head> <body> <script> var num1,num2,sum,res; num1 = Number(prompt('Enter the first number : ')); num2 = Number(prompt('Enter the first number : ')); sum = num1 + num2; if (sum == 20) { document.write("Sum is equal to 20"); } else { document.write("Sum is not equal to 20"); } </script> </body> </html>[/c] Output

else-if...else statement

shape Description

else-if...else checks more than one condition. When the condition of first if statement is false, then it checks for the next else-if block. If true, then it executes the statements of inner else-if block, otherwise, executes the statements of else block.

shape Syntax

if(condition1) { //statements; } else if(condition2) { //statements; } else { //statement }

shape Flow Chart

shape Example

[c] <!Doctype html> <html> <head> <title>Conditional Statements</title> <h2 style="color: Green">Example for else-if statement</h2> </head> <body bgcolor = "#E6E6FA"> <script> var vehicle = "Car"; if (vehicle == "Car") { alert("You will go by Car"); } else if(vehicle == "Aeroplane") { alert("You will go by Aeroplane"); } else { alert("You will go by some other vehicle"); } </script> </body> </html> [/c] Output Switch Statement will be explained in further chapters.

Summary

shape Key Points

  • If statement helps in decision making.
  • “If” block will be executed only when the set of JavaScript Conditions are true.
  • If-else statement has both true and false options.
  • else-if...else has multiple if and else blocks.