Thursday, October 29, 2015 8:25 PM

JavaScript If-else statements[BASICS]

PythonVery often when you write code, you want to perform different actions for different decisions.
You can use conditional statements in your code to do this.
In JavaScript we have the following conditional statements:
  • Use if to specify a block of code to be executed, if a specified condition is true
  • Use else to specify a block of code to be executed, if the same condition is false
  • Use else if to specify a new condition to test, if the first condition is false
  • Use switch to specify many alternative blocks of code to be executed
Note that if is in lowercase letters. Uppercase letters (If or IF) will generate a JavaScript error. 
Example:
<!DOCTYPE html>
<html>
<body>

<p>Click the button to display a time-based greeting:</p>

<button onclick="myFunction()">Try it</button>

<p id="demo"></p>

<script>
function myFunction() {
    var hour = new Date().getHours();
    var greeting;
    if (hour < 18) {
        greeting = "Good day";
    } else {
        greeting = "Good evening";
    }
    document.getElementById("demo").innerHTML = greeting;
}
</script>

</body>
</html>
Result:

Click the button to display a time-based greeting:

About Unknown

Here you can share some biographical information next to your profile photo. Let your readers know your interests and accomplishments.

No comments:

Post a Comment