JavaScript conditional statements

JavaScript conditional statements
Rate this post

If statement

The if statement is used to specify a block of JavaScript code that is executed, if a condition is true.

if (condition) {
   // code to be executed
   // ....
   // ...
}

 

Example
if (x < 5) {
   alert ("x is less than 5");
}

If You want to execute a single line of code in an if statement, is not necessarily to put curly braces in.
However it’s a good practice to always use curly braces!

if (x < 5) 
   alert ("x is less than 5");

 

The condition of equality

In a condition, if You want to check if two values are equal, use double or triple equal sign.

if (x == 5) {
   alert ("x is equal to 5");
}

The single equal sign is an assignment operator, it will set the value, not check the value.
For example x = 5, means that x gets the value 5.

To check if a variable is not equal to a value, use the exclamation mark and equal sign (!=), like:

if (x != 5) {
   alert ("x is not 5");
}

 

Else statement

The else statement is used to specify a new condition if the first condition is false.

If the first condition is true, will execute the code in the first block.
Otherwise, if first condition is false, will execute the code in the second block.

if (condition) {
    // code to be executed if the condition is true
} else {
    // code to be executed if the condition is false
}

 

Example
if (x < 5) {
   alert ("x is less than 5");
} else 
   alert ("x is greater than 5");
}

 

Else if statement

The else if statement is used to specify a new condition if the first condition is false.

if (condition1) {
    // code to be executed if condition1 is true
} else if (condition2) {
    // code to be executed if condition1 is false and condition2 is true
} else {
    // code to be executed if condition1 is false and condition2 is false
}

 

Example

We want to check on a scale from 1 to 10, if a value is small (1-3), medium (4-7) or large(8-10):

if (value <= 3) {
   alert ("value is small");
} else if (value >= 8) {
   alert ("value is large");
} else {
  alert ("value is medium");
}

 

Example
<h1>Choose a value:</h1>
<input type="field" id="myValue" maxlength="1" size="1"/>
<button type="button" id="myBtn">Send</button>
<script type="text/javascript">
document.getElementById("myBtn").onclick = function(x) {
	var x = document.getElementById("myValue").value;
	if (x <= 3) {
	   alert ("x is small");
	} else if (x >= 8) {
	   alert ("x is large");
	} else {
	  alert ("x is medium");
	}
};
</script>

Leave a Reply

Your email address will not be published. Required fields are marked *