JavaScript Switch Statement Absolute Beginner Lesson 14

JavaScript Switch statement is used when we have a lot of variables that we want to match. In the following example we get the day of the week. We can then show something for each day of the week.

Getting A Day JavaScript Built In Function

There are already functions that JavaScript comes with in every browser. The one we are going to use is they date. There are different variations of the date that you can get. We are going to focus on the day of the week. We use new Date().getDay to get the numbers 0 through 6. 0 is Sunday while 6 is Saturday.

Switch Statements in JavaScript

In Switch statements we try to match a variable. When that variable is matched we can then print out on the page what we want it to. In the following example in today’s lesson we are printing out the days of the week. Here is the code.

Only cool people share!

Code For Today’s Lesson

<p id="foo"></p>;
<script>
var boo = document.getElementById('foo');
var cday = new Date().getDay();
var day;
switch (cday){
case 0:
day = "Sunday";
break;
case 1:
day ="Monday";
break;
case 2:
day = "Tuesday";
break;
case 3:
day = "Wednesday";
break;
case 4:
day = "Thursday";
break;
case 5:
day = "Hey Its Friday";
break;
case 6:
day = "Saturday";
}
boo.innerHTML=day;
</script>

 

Next Lesson

JavaScript Switch Statement Absolute Beginner Lesson 14 was last modified: October 29th, 2021 by Maximus Mccullough
Summary
JavaScript Switch Statement Absolute Beginner Lesson 14
Article Name
JavaScript Switch Statement Absolute Beginner Lesson 14
Description
JavaScript Switch statement is used when we have a lot of variables that we want to match. In the following example we get the day of the week. We can then show something for each day of the week.
Author
Publisher
A1WEBSITEPRO LLC
Logo
javascript-switch-statment-absolute-beginners

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.