Skip to content

Single line if statement JavaScript | Best One Line syntax

  • by

One way is to use a ternary operator which works as a single line if statement in JavaScript. This is the best way, let’s see the example code:-

var canDrive = age > 16 ? 'yes' : 'no';

The ? : is called a ternary operator and acts just like an if/else when used in an expression

Examples of the single line if statement JavaScript

Ternary operator (Conditional operator)

<html>  
<head>  
    <title>Sample Code</title>  
    <script type="text/javascript">  
  	var age = 19;
	var canDrive = age > 16 ? 'YES' : 'No';
	alert(canDrive)
    </script>  
</head>  
</html> 

Output:

single line if statement JavaScript

Do comment if you have any doubts and question on this tutorial.

Note: The All JS Examples codes are tested on the Safari browser (Version 12.0.2) and Chrome.
OS: macOS 10.14 Mojave
Code: HTML 5 Version

Leave a Reply

Your email address will not be published. Required fields are marked *