If else conditional statement is very common in JavaScript. This logical condition checking is done inside a script as per the requirement. Here is the syntax for if else condition in JavaScript.
if(condition){
Code;
}else{
Code;
}
The first block is executed if the condition is TRUE and second block inside the else condition is executed if the condition is FALSE.
Let us learn one practical example and you can see this in action at confirm window tutorial. Here is the code.
var my_string = confirm("Are you satisfied with the quality of the tutorials here?");
if(my_string){
alert("Thank you");
}else{
alert("Please use the contact us page to give your feedbacks");
}
During execution of Script we frequently use if else condition checking. Here we will discuss few uses of it with code samples.
Checking numbers
We can check numbers by using if else condition. If numbers are less than fixed value then we can give a message.
<script type="text/javascript">
var n1=4;
var n2=6;
if(n2 > n1){
document.write("n2 is greater than n1 ");
}else {
document.write("n2 is not greater than n1 ");
}
</script>
Checking the length of user input
We have a form and we will check the input once the button is clicked. We will check the length of the string entered by user and accordingly give a message by using div layer.
<script type="text/javascript">
function check_t1(){
var t1=document.getElementById("t1").value;
if(t1.length < 2){
document.getElementById("msg").innerHTML="Enter Minimum 2 Chars ...";
}else{
document.getElementById("msg").innerHTML="it is more than 2 char length ...";
}
}
</script>
<input type=text name=t1 id=t1><input type=button onclick=check_t1(); value=Check>
<div id=msg></div>