JavaScript if statement | Basic code

  • by

JavaScript if statement is used to specify a block of code to be executed if a specified condition is true. Where The if keyword should be in lowercase letters.

if (condition) {
  //  block of code
} 

JavaScript if statement

Simple example code block of JavaScript code to be executed if a condition is true. If age is above 18 then only console log print the message.

<!DOCTYPE html>
<html>
<body>
  <script>

    var age =25;

    if( age > 18 ) {
     console.log("Qualifies for driving");
   }

 </script>
</body>
</html> 

Output:

JavaScript if statement

if…else statement

The ‘if…else’ statement is the next form of control statement that allows JavaScript to execute statements in a more controlled way.

Read examples: if…else statement

What is an if…else statement in JavaScript?

Answer: The if...else is a type of conditional statement that will execute a block of code when the condition in the if statement is truthy. If the condition is falsy, then the else block will be executed.

Any value that is not defined as falsy would be considered truthy in JavaScript.

Here is a list of  falsy values:

  • false
  • 0 (zero)
  • -0 (negative zero)
  • 0n (BigInt zero)
  • "", '', `` (empty string)
  • null
  • undefined
  • NaN (not a number)

Do comment if you have any doubts or suggestions on this JS if statement topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.