November 13, 2011 in Javascript, Programming, Tutorials by admin

Switch statements are very helpful conditional statements similar to ‘if statements’ but allow for a cleaner presentation when multiple if conditionals are required. If you have ever been curious how these work or are just reading about them for the first time, check this out.

Switch statements are quite simple and here is the basic structure of a JavaScript switch statement.

1
2
3
4
5
6
7
8
9
10
11
switch(v)
{
case 1:
executed code if case true 1
break;
case 2:
executed code if case true 2
break;
default:
the code to be executed if no cases above are true
}

Now that you have seen the basic structure, let us see it in action. Here is a very simple example where we will check against a string to see if it equals ‘hello’ and if so alert ‘hi’ back.

1
2
3
4
5
6
7
8
9
10
11
12
13
var n = 'hello';
switch(v)
{
case 'goodbye':
alert('bye');
break;
case 'hello':
alert('hi');
break;
default:
alert('Where are you?');
}

It really is that simple. If you have any questions about using switch statements please post them in the comments.