What is the selection statement in JS?

0 votes
26 views
Ravi Vishwakarma asked 11 days ago in Web Application by Ravi Vishwakarma

What is the selection statement in JS?

1 Answer

1 votes
Ethan Karla answered 10 days ago by Ethan Karla

We use the, selection statement to test a condition and decide the execution of a block of statements based on that condition result.The given condition then decides the execution of a block of statements. If the condition is true, then the block of statements is executed and if it is false, then the block of statements is ignored. Selection

statement are two type.

1. If statement
2. Switch statement
If statement
 if (condition)

  true block of statement
 else
  false block of statement
Example:
var company = window.prompt('Please enter your company', 'Your company name');
if (company != null) {
    document.write('Your company name : ' + company + ' <br/>');
}
else {
    document.write('Please enter your company name <br/>');
}
Switch Statement
 Using the switch statement, one can select only one option from more number of options very easily. In the switch statement, we provide a value that is to be compared with a value associated with each option. Whenever the given value matches the value associated with an option, the execution starts from that option. In the switch statement, every option is defined as a case.
Syntax:
switch(condition)

case 1:
 case 1 statement
 [break]
Case 2:
 case 2 statement
 [break]
Case n:
 case n statement
 [break]
default:
 default statement
 [break]
Example :
var color = window.prompt('Please enter your favorite color name', 'Your favorite color name');

switch (color.toLowerCase()) {
    case 'red':
        document.write('favorite color name is red <br />');
        break;
    case 'yellow':
        document.write('favorite color name is yellow <br />');
        break;
    case 'pink':
        document.write('favorite color name is pink <br />');
        break;
    case 'blue':
        document.write('favorite color name is blue <br />');
        break;
    default:
        document.write('favorite color name is black <br />');
        break;
}