How to use Conditional/Ternary Operator in Javascript

Conditional/Ternary Operator is used as an alternative to an if-else statement.

Lets see by an example.

Conditional/Ternary Operator

Now try using Conditional or Ternary operator

Know more about Conditional/Ternary operator by examples

[code javascript]

<script type="text/javascript">

var a = 999;

var result = (a>1000)?"Hey this is greater than 1000":"Sorry this is not greater than 1000";

console.log(result);

</script>

[/code]

Output: Sorry this is not greater than 1000

Explanation:
(a>1000) is checking for condition is true or false.
If this condition is true then
result variable is assigned with value "Hey this is greater than 1000"
If this condition is false then
result variable is assigned with value "Sorry this is not greater than 1000"

Output: Sorry this is not greater than 1000

Next example:

[code javascript]

<script type="text/javascript">

var a = 999;

var result = (a>1000 && a<=2000)?"Hey this is greater than 1000":"Sorry this is greater than 1000 and less than equal to 2000";

console.log(result);

</script>

[/code]

Output: Sorry this is greater than 1000 and less than equal to 2000

In this example, if the value is greater than 1000 and less than equal to 2000
then result variable assigned with "Hey this is greater than 1000"
otherwise
"Sorry this is greater than 1000 and less than equal to 2000"

But there is a bug, what happens if value 'a' is less than 1000
let's see

Actually for all false condition
the result is assigned with "Sorry this is greater than 1000 and less than equal to 2000"
Lets change in false section

[code javascript]

<script type="text/javascript">

var a= 999;

var result = (a>1000 && a<=2000)?"Hey, this is greater than 1000":(a<1000)?"Sorry this is less than 1000":"Sorry this is greater than 2000";

console.log(result);

</script>

[/code]

Output: Sorry this is less than 1000

I have replace false part by
(a<1000)?"Sorry this is less than 1000":"Sorry this is greater than 2000"
This is again a conditional statement.

Now you can see how can we use nested conditional statement.

Please watch the video carefully.

Click here to check other Javascript operators.
If you have any query. Feel free to ask.
I think You understand the concept of the conditional/Ternary operator in Javascript
Thanks