Skip to content
Related Articles

Related Articles

JavaScript Course | Conditional Operator in JavaScript
  • Last Updated : 26 Nov, 2019

Previous Topic: JavaScript Course | Logical Operators in JavaScript

Conditional operators allow us to perform different types of actions according to different conditions. We make use of the ‘if’ statement.

if(expression){
   do this;
}

The above argument named ‘expression’ is basically a condition that we pass into the ‘if’ and if it returns ‘true’ then the code block inside it will be executed otherwise not.
Example:




<script>
// if example
let age = 20;
if(age == 20){
  alert('Hola!'); // Hola!
}
</script>


Output:

Hola!

The above code is a very simple demonstration of if the conditional operator and if we change the value of age to something other than ’20’ then nothing prints.



How ‘if’ works
The ‘if(..)’ statements evaluates the expression inside its parentheses and then converts it into a boolean value. If that boolean value is a ‘false’ then the output will not be printed.

if(0){
console.log('hey'); // will not be printed
}
if(1){
console.log('Yo')// Yo
}

else clause
The else clause executes when the condition inside the if parenthesis fails.

if(this is true){
  do this;
}else{
  do this;
}

Example:




<script>
// else example
let age = 21;
if(age == 20){
  alert('You are 20'); // not executed
}else{
  alert('Adios!'); // will be alerted 
}
</script>


Output:

Adios!

There might be scenarios where we might have more than just two conditions, in that case, we make use of ‘else-if’ clause which requires a condition inside its parentheses.

if(expression){
  do this;
}else if(expression){
  do this;
}else{
  do this;
}

Example:




<script>
// else-if example
let age = 22;
if(age < 18 ){
  alert('Too Young.');
}else if( age > 18 && age < 60){
  alert('Yo..bienvenido.'); // Yo..bienvenido.
}else{
  alert('adios..señor');
}
</script>


Output:

Yo..bienvenido.

Ternary operator
In Javascript we also have a ternary operator which is a very short way of performing an action on based of a condition.

let result = condition ? value1 : value2;

It works similar to an if-else, where based on a condition we evaluate on result. In the above code snippet if the ‘condition’ evolves to ‘true’ then ‘value1’ will be executed otherwise ‘value2’ will be executed.
Example:




<script>
// ternany operator example
let age = 20;
let result = age>18 ? 'Great' : 'Not so great';
alert(result); // Great
</script>


Output:

Great

Next Topic: JavaScript Course | Javascript Prompt Example

full-stack-img

My Personal Notes arrow_drop_up
Recommended Articles
Page :