SimpleTuts.com

JavaScript if Statement

JavaScript Conditional Statements

Conditional statements are fundamental in JavaScript for making decisions in the code. These statements allow you to execute certain blocks of code based on whether a specified condition is true or false.

if Statement

The if statement in JavaScript is used for making decisions based on conditions. It allows you to execute a block of code only if a specified condition is true.

Here's a basic example of an if statement:


var age = 25;

if (age >= 18) {
  console.log("You are an adult."); // This will be executed
}

Explanation of the example:

You can extend the if statement with an else block to handle cases where the condition is false:


var age = 15;

if (age >= 18) {
  console.log("You are an adult.");
} else {
  console.log("You are a minor."); // This will be executed
}

In this example, age is 15, so the condition (age >= 18) evaluates to false. As a result, the code block inside the else statement is executed, outputting "You are a minor." to the console.

Simple if Example:


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Simple if example</title>
</head>
<body>
    <form action="">
        <label for="">Enter your age</label>
        <input type="number" id="age">
        <button onclick="votable();" type="button">Submit</button>
    </form>
    <script>
        function votable(){
            var age = Number(document.getElementById('age').value);

            if(age>=18){
                document.write("You are eligible for vote");
            }

            document.write("<br>Thank you");

        }
    </script>
    
</body>
</html>
Run Code

If else Example:


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>If else example</title>
</head>
<body>
    <form action="">
        <label for="">Enter your age</label>
        <input type="number" id="age">
        <button onclick="votable();" type="button">Submit</button>
    </form>
    <script>
        function votable(){
            var age = Number(document.getElementById('age').value);
            if(age>=18){
                document.write("You are eligible for vote");
            }else{
                document.write("You are not eligible for vote");
            }
            document.write("<br>Thank you");

        }
    </script>
    
</body>
</html>
Run Code