Explore the fundamental elements of conditional logic in JavaScript, including if-else statements, comparison operators, the Date object, and creating elements with JavaScript in this comprehensive tutorial.
This exercise is excerpted from Noble Desktop’s JavaScript for Front-End training materials and is compatible with JavaScript updates through 2023. To learn current skills in JavaScript with hands-on training, check out our Front-End Web Development Certificate, Full-Stack Web Development Certificate, and coding classes in-person and live online.
Topics covered in this JavaScript tutorial:
Conditional Logic: Using if-else statements, Single (=) vs. Double (==) Equal Signs, The Date Object, Creating Elements in a Page with JavaScript
Exercise Preview
Exercise Overview
In this exercise you’ll learn about if tests, the Date Object, and creating HTML elements via JavaScript.
Conditional Logic
There are times when you only want your JS code to be executed if certain criteria have been met. Programming languages rely on conditional logic to make decisions. The usual keywords are if and else. The logic boils down to:
- if a condition is true, do something
- else the condition is false, so do something else (or do nothing)
Getting Started
- For the first part of this exercise we’ll be working with the If-Else-Logic folder located in Desktop > Class Files > JavaScript Class. Open that folder in your code editor if it allows you to (like Visual Studio Code does).
- In your code editor, open if-else.html from the If-Else-Logic folder.
- Preview if-else.html in Chrome. (We’ll be using its DevTools.)
- Preview the file in the browser. The page is blank, but we’ll be using in the Console.
Writing an If Statement
- Switch back to your code editor.
-
In the script tag, write the if test shown below in bold. The comparison is done with a double equal sign because it’s checking something, not setting something.
<script> let inStock = true; if(inStock == true) { console.log('Item is in stock'); } </script>
Single (=) vs. Double (==) Equal Signs
= is an Assignment Operator
A single equal sign assigns (sets) a value: x = 8
x is assigned a value of 8.== is a Comparison Operator
A double equal sign compares (tests) values without changing them: x == 8
x is tested to see if it equals 8. If it does the test is true, otherwise it’s false. - Save and reload the page in Chrome.
-
Open the Console by hitting Cmd–Opt–J (Mac) or Ctrl–Shift–J (Windows).
You should see the message: Item is in stock
-
Back in your code editor, change the boolean to false as shown below:
let inStock = false; if(inStock == true) { console.log('Item is in stock'); }
-
Save and reload the page in Chrome.
There should be no message in the Console this time.
-
Back in your code editor, add an else statement with the following bold code:
let inStock = false; if(inStock == true) { console.log('Item is in stock'); } else { console.log('Item is out of stock'); }
-
Save and reload the page in Chrome.
In the Console you should see: Item is out of stock
More Comparison Operators
You just learned how to check equality. We can also compare numerical values to see if they are less than, equal to, or greater than. Comparisons Operators compare values and the result is either true or false.
Symbol | Comparison Operator | Example & Result |
---|---|---|
< | less than | 3 < 3 is false |
> | greater than | 3 > 3 is false |
== | equal to | 3 == 3 is true |
<= | less than or equal to | 3 <= 3 is true |
>= | greater than or equal to | 3 >= 3 is true |
-
Back in your code editor, below the existing test, add the following if statement using the less-than operator:
} let age = 16; if (age < 21) { console.log('Too young to vote'); } </script>
-
Save and reload the page in Chrome.
In the Console you should see: Too young to vote
The Date Object
The Date object returns an instance (a variable object) containing the full date-time from the user’s computer.
-
At the bottom of the script tag, instantiate an instance of the Date object as shown below in bold:
} let dateTime = new Date(); </script>
NOTE: This type of variable declaration, with the new keyword, is called the constructor method. To use the Date Object, we instantiate it using the constructor method with the resulting object instance has access to all the methods and properties of the Date object.
-
Log the dateTime object instance to the Console.
let dateTime = new Date(); console.log(dateTime);
-
Save and reload the page in Chrome.
In the Console you should get the entire date and time down to the second.
-
Let’s extract parts of the date we want (like the hour, month, year, etc.) by invoking methods of the Date object. Methods that return a property value and include get in the method name are known collectively as getters.
Get the current hour, month, and year by adding the following bold code:
console.log(dateTime); let hour = dateTime.getHours(); let month = dateTime.getMonth(); let year = dateTime.getFullYear();
-
Let’s output each part of the date onto a different line in the console. To create a new line we use
\n
as shown below:let year = dateTime.getFullYear(); console.log( hour + '\n' + month + '\n' + year + '\n' );
-
Save and reload the page in Chrome.
In the Console you should see 3 lines of numbers (hours, month, and year). The hour is in 24-hour military format, so 4 pm would appear as 16.
Using If Statements in a Page
Now that you’ve learned how if tests and dates work, let’s put them together in an actual webpage. We have a coffee shop website which offers different menus for breakfast, lunch, and dinner. To make it easier for visitors to quickly get to the menu for the current time of day, we’ll add a link to the appropriate menu. That will require us to get the current hour and then create a link to the appropriate menu.
- In your code editor, close any files you may have open.
- For the rest of this exercise we’ll be working with the GroundUp-Timely-Menu folder located in Desktop > Class Files > JavaScript Class. Open that folder in your code editor if it allows you to (like Visual Studio Code does).
- In your code editor, open index.html from the GroundUp-Timely-Menu folder.
-
Preview index.html in Chrome. (We’ll be using its DevTools.)
We’ll be adding the menu link below the main image (above the first heading).
- Leave the page open in the browser so we can come back and reload it later.
- Switch back to your code editor.
-
To get the current hour we’ll need to use the Date object, so add the following bold code in the script tag at the bottom of the page.
<script> let dateTime = new Date(); let hour = dateTime.getHours(); </script>
-
We need to write a conditional statement (which is a bit of logic) to figure out which of the 3 times of the day it is: breakfast (before 11am), lunch (11am up to 4pm), and dinner (4pm and later).
Add the following test. We’re let JavaScript do the math of 12 + 4 to give us the hour in the appropriate 24-hour format. You could enter 16 instead, if you prefer.
<script> let dateTime = new Date(); let hour = dateTime.getHours(); if (hour < 11) { } else if (hour < (12+4)) { // 4pm } else { }; <script>
-
The link will need an href for the appropriate page and some text for inside the link. Let’s store these in variables we’ll use later when creating the link.
If we define variables inside an if statement, they can only be used inside that statement. We’ll be creating the link outside the if statement, so add the following bold code to define empty variables outside the if statement. Later we’ll change the contents of these variables inside the if statement.
let dateTime = new Date(); let hour = dateTime.getHours(); let linkText; let linkHref; if (hour < 11) {
-
Now we can set the appropriate text and href depending on the test. Add the following bold code:
if (hour < 11) { linkText = 'Breakfast'; linkHref = 'breakfast.html'; } else if (hour < (12+4)) { // 4pm linkText = 'Lunch'; linkHref = 'lunch.html'; } else { linkText = 'Dinner'; linkHref = 'dinner.html'; };
Creating Elements in a Page with JavaScript
Now that we have the appropriate text and href, we can create a link with those attributes and add it to our page.
-
An HTML link is an
<a>
tag. Below the if statement, add the following bold code to create a new one with JavaScript:}; let menuLink = document.createElement('a'); </script>
-
This new element has been created in the browser’s memory, but we have not told JavaScript where in the page to put it. On line 31 notice this empty element:
<div id="current-menu"></div>
We want to add our link into this element, so take note if it’s ID.
-
Add the following bold code to put our link into that div:
let menuLink = document.createElement('a'); document.getElementById('current-menu').appendChild(menuLink); </script>
-
Save and reload the page in Chrome.
You won’t see anything on the page yet, because the link does not have any text. We can verify the tag has been made using the DevTools though.
- Ctrl–click (Mac) or Right–click (Windows) on the heading Amazing Coffee, Made To Order and choose Inspect.
-
In the DevTools, above the currently selected h3, click the triangle next to
<div id="current-menu">
to expand it.Inside you should an empty link
<a></a>
- Switch back to your code editor.
-
To put text into the link, add the following bold code (paying very close attention to the space character inside the single quotes!
let menuLink = document.createElement('a'); menuLink.innerHTML = linkText + ' Menu'; document.getElementById('current-menu').appendChild(menuLink);
-
The link also needs an href so it knows where to go when people click it, so add the following bold code:
let menuLink = document.createElement('a'); menuLink.innerHTML = linkText + ' Menu'; menuLink.href = linkHref; document.getElementById('current-menu').appendChild(menuLink);
-
Save and reload the page in Chrome.
- You should see a link that says Dinner Menu (or whatever time of day you’re doing this exercise).
- Click the link and it should take you to that page (the menu pages are placeholder without much content, just so you can see it works).
Great, our link is working properly!
- Switch back to your code editor.
-
One last thing… the link is not styled. We have a button class defined in our CSS, so let’s assign that to the link by adding the following bold code:
menuLink.href = linkHref; menuLink.className = 'button'; document.getElementById('current-menu').appendChild(menuLink);
-
Save and reload the page in Chrome.
You should now have a nicely styled button that links to the appropriate menu for the current time of day. Nice!