JavaScript Conditional Statements Part 1
In this JavaScript tutorial, you will learn about the conditional statements available in JavaScript for decision making, if statement and if…else statement.
Just like any other programming language, conditional statements in JavaScript are used for decision making purpose.
The conditional statements available in JavaScript for decision making are:
- if statement
- if…else statement
- if…else if….else statement
- switch statement
NOTE: All syntax specified above must be written exactly as above since JavaScript is a case-sensitive language.
if statement:
If a programmer wants to execute certain statements only when a desired condition is satisfied or has true value then conditional if statement is used.
General syntax of if statement in JavaScript is as follows:
|
Let us see an example to understand this concept:
|
Output of the above script as produced in a HTML page is shown below:
In the above example, if block will be executed only when value of the variable is less than 30. In our example, the value of variable exforsys is 20 (which is less than 30) hence if block is executed and the output Welcome is printed.
if…else statement:
This conditional structure is used in JavaScript if a programmer wants to execute a certain block of statements if a condition is true and execute another block of statements if the condition returns false value.
General syntax of this if…else structure in a JavaScript is as follows:
|
For example
|
Output of the above script as produced in a HTML page is shown below:
In this example,if block is executed only when the value of variable exforsys is less than 30, otherwise else block will get executed, since the value of variable exforsys in our example is 40, else block is executed and the output Thank You! is printed.