Skip to content

if condition in JavaScript | Basics

  • by

The JavaScript if condition statement executes a code block if a specified condition is true. If the condition is false, then a block of code will not be executed.

if (expression) {
   //Statement(s) to be executed if expression is true
}

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.

if (condition) {
  //  Executed if the condition is true
} else {
  //  Eexecuted if the condition is false
}

if condition in JavaScript

Simple example code understands how the if statement works.

<!DOCTYPE html>
<html>
<body>
  <script >
   var age = 20;

   if( age > 18 ) {
    console.log("Qualifies for driving 18 <", age);
   }
 </script>
</body>
</html>

Output:

if condition in JavaScript

More example

function testNum(a) {
  let result;
  if (a > 0) {
    result = 'positive';
  } else {
    result = 'NOT positive';
  }
  return result;
}

console.log(testNum(-5)); // "NOT positive"

Do comment if you have any doubts or suggestions on this JS condition 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. Required fields are marked *