Friday 24 August 2018

JavaScript: Decision Making: if, if-then

if statement
"if" tell the program execute the section of code when the condition evaluates to true.

Syntax
if(condition){
         // Executes if the condition true
}

if.html
<!DOCTYPE html>

<html>

<head>
    <title>if statement</title>
</head>

<body>
    <script type="text/javascript">
        var a = prompt("Enter any Integer", 100);

        if (a % 2 == 0) {
            document.write("You entered even number");
        }
    </script>
</body>

</html>

Open above html file in browser, it prompts for input. If you enter even number, it prints the message 'You entered even number' else it prints nothing.

if-else statement
If the condition true, then if block code executed. other wise else block code executed.

Syntax:
if(condition){

}
else{

}

ifelse.html
<!DOCTYPE html>

<html>

<head>
    <title>if-else statement</title>
</head>

<body>
    <script type="text/javascript">
        var a = prompt("Enter any Integer", 100);

        if (a % 2 == 0) {
            document.write("You entered even number");
        } else {
            document.write("You entered odd number");
        }
    </script>
</body>

</html>

Open above html file in browser, it prompts for input. If you enter even number, it prints the message 'You entered even number' else it prints "You entered odd number".

Previous                                                 Next                                                 Home

No comments:

Post a Comment