Friday, November 15, 2024
Google search engine
HomeLanguagesJavascriptJavaScript Course Conditional Operator in JavaScript

JavaScript Course Conditional Operator in JavaScript

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:

javascript




// if example
let age = 20;
if(age == 20){
  console.log('Hola!'); // Hola!
}


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(..)’ statement 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')// Will print Yo
}

How ‘else’ works?:

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

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

Example: In this example we will show you the if.. else statement example./p>

JavaScript




// else example
let age = 21;
if(age == 20){
      console.log('You are 20'); // Not executed
}else{
      console.log('Adios!'); // Will be alerted 
}


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: In this example we will show you the else-if condition, this will occur when there are multiple conditions.

javascript




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


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 similarly to an if-else, where based on a condition we evaluate on the result. In the above code snippet if the ‘condition’ evolves to ‘true’ then ‘value1’ will be executed otherwise ‘value2’ will be executed.

Example:

javascript




// Ternary Operator Example
let age = 20;
let result = age>18 ? 'Great' : 'Not so great';
console.log(result); // Great


Output:

Great

RELATED ARTICLES

Most Popular

Recent Comments