Skip to main content
March 23, 2026Dan Rodney/8 min read

If Else, the Date Object, & Creating Elements

Master JavaScript Conditionals and Dynamic Element Creation

Core JavaScript Concepts You'll Learn

Conditional Logic

Learn if-else statements to make your code execute only when specific criteria are met. Master the foundation of programming decision-making.

Date Object Manipulation

Harness JavaScript's Date object to retrieve current time information and create time-based functionality in your applications.

Dynamic Element Creation

Build HTML elements programmatically using JavaScript's createElement method to add interactive content to your web pages.

Topics Covered in This JavaScript Tutorial:

Master essential JavaScript fundamentals including conditional logic with if-else statements, understanding assignment versus comparison operators (= vs. ==), leveraging the Date Object for dynamic content, and programmatically creating DOM elements with JavaScript. These core concepts form the foundation of interactive web development.

Exercise Preview

preview if else

Exercise Overview

In this hands-on exercise, you'll build a dynamic menu system that automatically displays contextually relevant content based on the current time. You'll master if-else conditional logic, harness the Date Object for real-time data, and learn to create and manipulate HTML elements programmatically—skills that are essential for modern web applications and user experience optimization.

Understanding Conditional Logic

Professional JavaScript development relies heavily on conditional logic—the ability to execute different code paths based on specific criteria. This fundamental programming concept enables dynamic, responsive applications that adapt to user behavior, system states, and real-time data. The core structure uses if and else keywords to create decision trees:

  • if a condition evaluates to true, execute a specific block of code
  • else the condition is false, execute an alternative block (or skip execution entirely)

This pattern is ubiquitous in modern web development, from form validation to API response handling and user interface state management.

The Foundation of Programming Logic

Conditional logic is essential for creating intelligent applications. Every programming language relies on if-else statements to make decisions based on different criteria.

Getting Started

Let's establish our development environment and examine the foundational files for this exercise.

  1. Navigate to the If-Else-Logic folder located in Desktop > Class Files > JavaScript Class. Open this folder in your preferred code editor (Visual Studio Code, Sublime Text, or similar).
  2. In your code editor, open if-else.html from the If-Else-Logic folder.
  3. Launch if-else.html in Chrome browser—we'll be utilizing Chrome DevTools for debugging and console output throughout this exercise.
  4. The page appears blank initially, which is expected. We'll be working primarily with the JavaScript Console to observe our code execution and results.

Writing Your First If Statement

Now we'll implement a basic conditional statement to control program flow based on inventory status—a common real-world scenario in e-commerce applications.

  1. Return to your code editor.
  2. Within the script tag, add the following conditional logic. Notice we use the double equal sign (==) for comparison rather than assignment:

    <script>
       let inStock = true;
       if(inStock == true) {
          console.log('Item is in stock');
       }
    </script>

Critical Distinction: Single (=) vs. Double (==) Equal Signs

= is an Assignment Operator
A single equal sign assigns a value to a variable: let x = 8 stores the value 8 in variable x. This is a destructive operation that changes the variable's state.

== is a Comparison Operator
A double equal sign compares two values without modifying them: x == 8 tests whether x equals 8, returning true or false. This is a non-destructive evaluation that forms the basis of conditional logic.

Professional Tip: Modern JavaScript also includes the strict equality operator (===), which checks both value and data type, providing more predictable behavior in complex applications.

  • Save your file and reload the page in Chrome.
  • Access the Console using Cmd–Opt–J (Mac) or Ctrl–Shift–J (Windows).

    You should observe the message: Item is in stock

  • Back in your code editor, modify the boolean value to false:

    let inStock = false;
    if(inStock == true) {
       console.log('Item is in stock');
    }
  • Save and reload the page in Chrome.

    The Console should now be empty—our condition evaluated to false, so no code executed.

  • Now add an else clause to handle the false condition:

    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.

    The Console should now display: Item is out of stock

  • Assignment vs Comparison Operators

    FeatureSingle = (Assignment)Double == (Comparison)
    PurposeSets a valueTests/compares values
    ExampleX = 8X == 8
    ResultVariable is changedReturns true or false
    Use CaseVariable declarationConditional statements
    Recommended: Always use == in if statements to avoid accidentally changing variable values

    Mastering Comparison Operators

    Beyond simple equality checks, JavaScript provides a complete suite of comparison operators for evaluating numerical relationships. These operators are essential for creating sophisticated business logic, from age verification systems to pricing calculations and data validation.

    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

    Let's implement a practical age verification system using these operators:

    1. Below your existing conditional logic, add this age verification check:

      }
      
         let age = 16;
         if (age < 21) {
            console.log('Too young to vote');
         }
      </script>
    2. Save and reload the page in Chrome.

      The Console should display: Too young to vote

    Leveraging the Date Object

    The JavaScript Date Object provides powerful functionality for time-based applications, from scheduling systems to analytics dashboards. Understanding date manipulation is crucial for creating dynamic, time-aware web applications that respond to real-world timing constraints.

    1. At the bottom of your script tag, instantiate a Date object instance:

      }
      
         let dateTime = new Date();
      </script>

      Technical Note: This constructor pattern using the new keyword creates an object instance containing the current date and time from the user's system. This instance provides access to numerous methods for date manipulation and formatting—essential for building professional time-sensitive applications.

    2. Output the complete dateTime object to examine its structure:

      let dateTime = new Date(); 
      console.log(dateTime);
    3. Save and reload the page in Chrome.

      The Console displays the full timestamp, including date, time, timezone, and milliseconds—valuable data for debugging and logging.

    4. Extract specific date components using getter methods—specialized functions that retrieve particular properties from the Date object:

      console.log(dateTime);
      let hour = dateTime.getHours();
      let month = dateTime.getMonth();
      let year = dateTime.getFullYear();
    5. Format the output for better readability using the newline character (\n):

      let year = dateTime.getFullYear();
      console.log( hour + '\n' + month + '\n' + year + '\n' );
    6. Save and reload the page in Chrome.

      The Console displays three separate lines showing hours (in 24-hour format), month (0-indexed), and year. Note that 4 PM appears as 16, following the international 24-hour standard used in most programming contexts.

    Constructor Method Pattern

    The 'new' keyword creates an instance of the Date object using the constructor method. This pattern gives you access to all Date object methods and properties.

    Essential Date Object Methods

    getHours()

    Returns the current hour in 24-hour military format. 4 PM appears as 16, making it perfect for time-based conditionals.

    getMonth()

    Retrieves the current month as a number. Remember that months are zero-indexed, so January is 0 and December is 11.

    getFullYear()

    Returns the complete four-digit year. Use this instead of getYear() which returns a two-digit year that can cause confusion.

    Building Dynamic Page Content with Conditional Logic

    Now we'll apply these concepts to solve a real business challenge: automatically displaying relevant menu options based on the current time of day. This approach improves user experience by reducing cognitive load and directing visitors to contextually appropriate content.

    1. Close any open files in your code editor.
    2. Navigate to the GroundUp-Timely-Menu folder in Desktop > Class Files > JavaScript Class. Open this folder in your code editor.
    3. Open index.html from the GroundUp-Timely-Menu folder.
    4. Preview index.html in Chrome.

      We'll dynamically insert a time-appropriate menu link below the hero image, above the main heading—a prime location for user attention and engagement.

    5. Keep the browser tab open for testing our changes.
    6. Switch back to your code editor.
    7. Initialize our Date object to capture the current time:

      <script>
         let dateTime = new Date();
         let hour = dateTime.getHours();
      </script>
    8. Implement business logic to categorize time periods: breakfast (before 11 AM), lunch (11 AM to 4 PM), and dinner (4 PM onwards). This creates a comprehensive day-part targeting system:

      <script>
         let dateTime = new Date();
         let hour = dateTime.getHours();
      
         if (hour < 11) {
      
         }
         else if (hour < (12+4)) {  // 4pm in 24-hour format
      
         }
         else {
      
         };
      <script>
    9. Declare variables outside the conditional blocks to ensure they're accessible throughout the script scope—a critical concept in JavaScript variable management:

      let dateTime = new Date();
      let hour = dateTime.getHours();
      let linkText;
      let linkHref;
      
      if (hour < 11) {
    10. Populate variables with time-appropriate content and navigation targets:

      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';
      };
    The Foundation of Programming Logic

    Conditional logic is essential for creating intelligent applications. Every programming language relies on if-else statements to make decisions based on different criteria.

    Dynamic DOM Manipulation with JavaScript

    Modern web applications require the ability to create and modify HTML elements programmatically. This technique enables responsive interfaces that adapt to user interactions, API responses, and changing application states without requiring page reloads.

    1. Create an anchor element using JavaScript's DOM manipulation capabilities:

      };
      
         let menuLink = document.createElement('a');
      </script>
    2. Locate the target container in your HTML. On line 31, you'll find:

      <div id="current-menu"></div>

      This empty div serves as our insertion point for the dynamically generated menu link.

    3. Inject the newly created element into the DOM structure:

      let menuLink = document.createElement('a');
         document.getElementById('current-menu').appendChild(menuLink);
      </script>
    4. Save and reload the page in Chrome.

      The element exists in memory and DOM structure but remains invisible without content. We can verify its creation using Chrome DevTools.

    5. Ctrl–click (Mac) or Right–click (Windows) on the heading Amazing Coffee, Made To Order and select Inspect Element.
    6. In DevTools, expand the <div id="current-menu"> element by clicking its triangle.

      You'll see an empty anchor tag <a></a>—proof our JavaScript successfully created the element.

    7. Return to your code editor.
    8. Populate the link with contextual text content:

      let menuLink = document.createElement('a');
      menuLink.innerHTML = linkText + ' Menu';
      document.getElementById('current-menu').appendChild(menuLink);
    9. Configure the link's navigation target using the href attribute:

      let menuLink = document.createElement('a');
      menuLink.innerHTML = linkText + ' Menu';
      menuLink.href = linkHref;
      document.getElementById('current-menu').appendChild(menuLink);
    10. Save and reload the page in Chrome.

      • A contextually appropriate link should appear (e.g., Dinner Menu in the evening).
      • Test the link functionality—it should navigate to the corresponding menu page.

      Excellent! Our dynamic link system is operational and responsive to real-time conditions.

    11. Switch back to your code editor.
    12. Apply CSS styling by assigning a pre-defined class to enhance visual presentation:

      menuLink.href = linkHref;
      menuLink.className = 'button';
      document.getElementById('current-menu').appendChild(menuLink);
    13. Save and reload the page in Chrome.

      Your time-aware menu system now displays a professionally styled button that automatically adapts to the current time of day—demonstrating the power of combining conditional logic with DOM manipulation for enhanced user experience.

    Key Takeaways

    1Conditional logic using if-else statements allows JavaScript code to execute only when specific criteria are met
    2Single equal signs (=) assign values while double equal signs (==) compare values without changing them
    3JavaScript provides multiple comparison operators including less than (<), greater than (>), and equal to (==) for different testing scenarios
    4The Date object uses the constructor method pattern with 'new' keyword to create instances with access to date manipulation methods
    5Getter methods like getHours(), getMonth(), and getFullYear() extract specific parts of date information for conditional logic
    6Dynamic element creation involves three steps: createElement(), setting properties, and appendChild() to insert into the DOM
    7Variables declared inside if statements have limited scope, so declare them outside when needed elsewhere in your code
    8Real-world applications combine multiple JavaScript concepts like conditionals, date objects, and DOM manipulation to solve practical problems

    RELATED ARTICLES