Tutorials

Learn web design and programming with our free video and text tutorials.

Javascript Switch Statements Tutorial

Javascript conditional statements allow you execute certain statements depending on if a condition is met. The switch statement is used to select one many blocks of code to be executed.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>WebDevelopmentTutorials.com</title>
</head>
<body>

<script type="text/javascript" language="javascript">

switch(n)
{
case 1:
execute code block 1
break;
case 2:
execute code block 2
break;
default:
code to be executed if n is
different from case 1 and 2
}

</script>

</body>
</html>

The javascript code below will display the day that it is.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>WebDevelopmentTutorials.com</title>
</head>
<body>

<script type="text/javascript" language="javascript">

var d = new Date()
theDay=d.getDay()
switch (theDay)
{
case 0:
document.write("Today is Sunday.")
break
case 1:
document.write("Today is Monday.")
break
case 2:
document.write("Today is Tuesday.")
break
case 3:
document.write("Today is Wednsday.")
break
case 4:
document.write("Today is Thursday.")
break
case 5:
document.write("Today is Friday.")
break
case 6:
document.write("Today is Saturday.")
}

</script>

</body>
</html>

The javascript above displays: