Sometimes you want to check if we meet 2 or more conditions in JavaScript. To accomplish this we use the OR "||", AND "&&" statements within the IF condition. In the last lesson we were checking the date. If a certain date met the condition we displayed something. What if we had a couple of dates where we wanted to display something? Lets see how this can accomplish this in JavaScript.
new Date().getDay
We can get the number of the day with a JavaScript function. Notice that the first number in this function starts with "0". So Sunday would be equal to "0" and Saturday would be equal to "6". If you use the code below, it will display today's day.<script> var x = document.getElementById('foo'); var y = new Date().getDay(); x.innerHTML=y;</script></pre> <h2>Using OR || in The Condition Statement</h2> Now what we want to do is display "It's The Weekend" on Friday, Saturday and Sunday. On the rest of the days we will display, "Have a nice day". Lets see how this is accomplished. <pre class="EnlighterJSRAW" data-enlighter-language="generic"><script> var x = document.getElementById('foo'); var y = new Date().getDay(); if(y==5 || y==6 || y==0){ x.innerHTML="Its The Weekend!"; }else{ x.innerHTML="Have A Nice Day"; } </script>
Explanation of Code
This will give us the number of the current day. We store that in a variable called "y". Next we started our if statement and conditions. We are checking to see if the day is Friday, Saturday, or Sunday. If it is, then we display, "It's The Weekend". We then use the "else" statement for every other day to display, "Have a Nice Day". Now let's go over using "AND &&" in the conditions statement on the next page.Using "AND &&" in The Conditions Statement
Sometimes we need to check and see if 2 condition are met. Let's say we wanted to display "Its the Weekend In June" in June. Then for rest of the months we just want to say "It's the Weekend". How can we accomplish this? Look at this code.<script> var x = document.getElementById('foo'); var y = new Date().getDay(); var z = new Date().getMonth(); if(y==5 || y==6 || y==0 && z==5){ x.innerHTML="Its The Weekend in June!"; }else if(y==5 || y==6 || y==0){ x.innerHTML="Its the weekend"; }else{ x.innerHTML="Have a Nice Day"; } </script>