Free Web Development Online Tutorials, Learn to Code
Learn JavaScript, Free JavaScript Tutorial for Beginners, Interactive JavaScript Examples

javascript if else Statement

Here we learn how to write if else statement in JavaScript, if-else also known as conditional statement, is one of the very common statement in all programming language, but everywhere there are some difference in syntax.

Use of If else Statement in javascript

If-else statement can be written in different ways while writing any JavaScript function

  • if

    if(condition)
    {
        // action code
    }
    

  • if else

    if(condition)
    {
        // action code 1
    }
    else
    {
        // action code 2
    }
    

  • if else if

    if(condition 1)
    {
        // action code 1
    }
    else if (condition 2)
    {
        // action code 2
    }
    

  • nested if or/and if else

    if(condition)
    {
            // nested if else 
            if(condition)
            {
            }
            else 
            {
            }
    }
    

javascript if else syntax with example

Here we learn JavaScript if else syntax with some example.

so we create a form where we receive user input, if user type India then we display a message saying “You are Indian” else will display “Not sure, if you are Indian!”

Type your country name

Here is the code.
Remember that JavaScript is always case sensitive, so before you compare you should convert the input into either toLowerCase() or toUpperCase()

<script>
function checkInput() 
{
    var _input = document.getElementById("txtInput").value;            
if (_input != "" || _input != null) {
    var _formatedInput = _input.toLowerCase();
            
        if (_formatedInput == "india") {
            alert("You are Indian.");
        }
        else {
            alert("Not sure, if you are India!");
        }
   }         
}
</script>

Additionally you can also make sure if there is no space in the input string, using trim function you can remove space from both sides.

<script>
var _input = "Hello World   ";
var _inputTrimed = _input.trim();
 
</script>

Comment
Name
Email
Website
Subscribe