How to write an inline IF statement in JavaScript ?
Last Updated :
29 May, 2019
We can write an inline IF statement in javascript using the methods described below.
Method 1: In this method we write an inline IF statement Without else, only by using the statement given below.
Syntax:
(a < b) && (your code here)
Above statement is equivalent to
if(a < b){
// Your code here
}
Example: Below is the implementation of above approach:
<script>
function max(n, m){
(n > m) && document.write(n + "<br>" );
(m > n) && document.write(m + "<br>" );
}
var a = -10;
var b = 5;
max(a, b);
a = 50;
b = 20;
max(a, b);
</script>
|
Output:
5
50
Method 2: In this method, we will use ternary operator to write inline if statement.
Syntax:
result = condition ? value1 : value2;
If condition is true then value1 will be assigned to result variable and if wrong then value2 will be assigned.
Example: Below is the implementation of above approach:
<script>
function max(n, m){
var x = (n > m) ? n : m;
return x;
}
var a = -10;
var b = 5;
var res;
res = max(a, b);
document.write(res + "<br>" );
a = 50;
b = 20;
res = max(a, b);
document.write(res + "<br>" );
</script>
|
Output:
5
50
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...