Function of “switch()” in JavaScript

Asked By 10 points N/A Posted on -
qa-featured

What is the function of  "switch()"  in JavaScript and where i can place it  in Html document?

SHARE
Best Answer by Sharath Reddy
Answered By 0 points N/A #98249

Function of “switch()” in JavaScript

qa-featured

Hi there

I Think you need help regarding the switch() statement in JavaScript.

Java provides a several branch variety statement known as switch. This selection statement checks the significance of an expression against a list of integer or char constants. When a match is found , the statements associated with that constant are executed.

The syntax of the switch statement is as follows : –

switch(expression)

{

case constant1 : statement sequence 1 ;

break;

case constant2 : statement sequence 2 ;

break;

case constant3 : statement sequence 3 ;

break;

default : statement sequence when provided input is not in any of the above cases ;

}

Use break statement or also you will have a situation called fall through , Its the fall of control to the following case of the matching case.

Good luck.

Best Answer
Best Answer
Answered By 563020 points N/A #98251

Function of “switch()” in JavaScript

qa-featured

The switch statement is used in JavaScript to make different action according to different conditions. It is used to execute different events or tasks based on the source value.

Here is the proper syntax for the switch statement:

switch(n)
{
case 1:
  first block to execute
  break;
case 2:
  second block to execute
  break;
default:
  block to execute if n doesn’t match with case 1 and case 2
}

At the start, the set will have an expression n that needs to be evaluated once. The value of n will then be compared with the value in every case. If it matches with one of the cases, the block of codes under it will be executed. Inserting break; after each condition avoids the code from going over to the next case.

To better understand it and maybe learn some other JavaScript statements, you may visit JavaScript Switch Statement.

Login/Register to Answer

Related Questions