• Tutorials Logic, IN
  • +91 8092939553
  • info@tutorialslogic.com

Conditional Statements in JavaScript

Conditional Statements

A conditional statement refers to a piece of code that does the things based on some condition. When we write code, we will often need to use these conditional statements. There are besically four types of conditional statements-

  • The if statements.
  • The if-else statements.
  • The if-else-if statements.
  • The switch case statements.

The if Statements

The if statement is used to execute a block of code only if the specified condition is true.

										    
											if(condition) {
												statement;
											}
											
										
										    
											if(7 > 5) {
												console.log('True');
											}
											
										

The if-else Statements

										    
											if(condition) {
												statement 1;
											} else {
												statement 2;
											}
											
										
										    
											if(5 > 7) {
												console.log('True');
											} else {
												console.log('False');
											}
											
										

The if-else-if Statements

The if-else-if statement is used to execute a block of code only if the specified condition is true from the several condition.

										    
											if(condition) {
												statement 1;
											} else if {
												statement 2;
											} else {
												statement 3;
											}
											
										
										    
											if(5 > 7) {
												console.log('Greater');
											} else if (5 == 7) {
												console.log('Equals');
											} else {
												console.log('Smaller');
											}
											
										

The switch case Statements

The switch case statement evaluates an expression, and then matching its value to a case clause, once match case is found, it executes statements associated with that case.

										    
											switch(expression) {
												case value 1:
												    statement;
													break;
													
												case value 2:
												    statement;
													break;
													
												default:
												    statement;
											}
											
										
										    
											let value = 2;
											
											switch (value) {
												case 1:
												    console.log('Too small');
													break;
												case 2:
												    console.log('Exactly!');
													break;
												case 3:
												    console.log('Too large');
													break;
												default:
												    console.log('Unknown');
											}