Control Flow in JavaScript – Conditionals and Loops

Introduction:

Welcome to the fascinating world of JavaScript control flow, an essential concept for developing dynamic web applications, including web3 projects.

Control flow statements dictate the order in which your code executes, allowing you to make decisions and repeat actions based on certain conditions.

Remember, watching the lesson video will offer a deeper understanding of this topic.

Learning Objectives:

By the end of this lesson, you will be able to:

  1. Understand and implement conditional statements like if/else and switch in JavaScript.
  2. Utilize loops (for, while, and do...while) to execute code repeatedly under specific conditions.
  3. Learn about different control flow and their usage in JavaScript programs.

Lesson Video:


1.0 Conditional Statements:

Conditional statements enable your program to decide which blocks of code to execute based on certain conditions. JavaScript offers if/else and switch statements for this purpose:

1.1 If/Else Statements:

Basic Syntax:

if (condition) {
        // Code to execute if condition is true 
   } else { 
        // Code to execute if condition is false 
}

These statements check a condition and execute the corresponding code block based on the result (true or false).

For multiple conditions, else if can be used.

1.2 Switch Statements:

A switch statement compares a variable against multiple cases and executes the matching block of code.

Syntax:

switch(variable) {
  case value1:
    // Code for value1
    break;
  case value2:
    // Code for value2
    break;
  default:
    // Code if no match is found
}

2. JavaScript Loops:

Loops are used to repeat actions:

2.1 For Loop:

Syntax:

for (initialization; condition; increment) {
  // Code to be executed on each iteration
}

Ideal for situations where you know how many times you need to repeat an action.

2.2 While Loop:

Syntax:

while (condition) {
  // Code to be executed as long as condition is true
}

Useful when the number of iterations is not known beforehand.

2.3 Do…While Loop:

The do...while loop is similar to the while loop but ensures that the code block is executed at least once.

Syntax:

do {
  // Code to be executed
} while (condition);

Example Codes for Practical Application:

Expanding the Capstone Project

Expanding on our Token Minter dApp, let’s enhance its features using what you learned from this lesson.

Existing Capstone Project Code from Previous Lesson:

Javascript Code:

// External JavaScript file for the global script
 
// Declare a variable to track the total minted tokens
let totalMintedTokens = 0;
 
document.addEventListener('DOMContentLoaded', function() {
    // Access the mint button and input fields
    const mintButton = document.querySelector('#mint button');
    const walletInput = document.querySelector('#walletAddress');
    const tokenInput = document.querySelector('#tokenAmount');
 
    // Event listener for the mint button
    mintButton.addEventListener('click', function() {
        let walletAddress = walletInput.value;
        let tokenAmount = parseInt(tokenInput.value);
 
        // Update the total minted tokens without validation
        updateMintedTokens(tokenAmount);
 
        // Notify the user about the minting process
        alert(`Minting ${tokenAmount} tokens to wallet: ${walletAddress}`);
 
        // TODO: In the next lesson, we will add validation to check the correctness of the wallet address and token amount. 
        // It's important to validate and sometimes sanitize user inputs for security and functionality.
    });
});
 
// Function to update the total minted tokens
function updateMintedTokens(amount) {
    // Add the specified amount to the total minted tokens
    totalMintedTokens += amount;
    document.getElementById('totalMinted').textContent = `Total Minted: ${totalMintedTokens}`;
}

CSS Code:

// External JavaScript file for the global script

// Declare a variable to track the total minted tokens
let totalMintedTokens = 0;

document.addEventListener('DOMContentLoaded', function() {
    // Access the mint button and input fields
    const mintButton = document.querySelector('#mint button');
    const walletInput = document.querySelector('#walletAddress');
    const tokenInput = document.querySelector('#tokenAmount');

    // Event listener for the mint button
    mintButton.addEventListener('click', function() {
        let walletAddress = walletInput.value;
        let tokenAmount = parseInt(tokenInput.value);

        // Validation for wallet address and token amount
        if(walletAddress !== '' && !isNaN(tokenAmount) && tokenAmount > 0) {
            // Update the total minted tokens
            updateMintedTokens(tokenAmount);

            // Notify the user about the minting process
            alert(`Minting ${tokenAmount} tokens to wallet: ${walletAddress}`);
        } else {
            // Alert for invalid input
            alert('Please enter a valid wallet address and a positive number of tokens to mint.');
        }
    });
});

// Function to update the total minted tokens
function updateMintedTokens(amount) {
    // Add the specified amount to the total minted tokens
    totalMintedTokens += amount;
    document.getElementById('totalMinted').textContent = `Total Minted: ${totalMintedTokens}`;
}

HTML Code:

<!DOCTYPE html> <!-- Defines document type and HTML version -->
<html lang="en"> <!-- Sets the language of the page -->

<head>
    <meta charset="UTF-8"> <!-- Sets character encoding for the document -->
    <meta name="viewport" content="width=device-width, initial-scale=1.0"> <!-- Ensures proper rendering on mobile devices -->
    <title>Token Minter dApp</title> <!-- Title of the webpage -->
    <link rel="stylesheet" href="/globalstyles.css"> <!-- Link to external CSS file -->
</head>

<body>
    <header>
        <!-- Site header with navigation -->
        <h1>Token Minter dApp</h1>
        <nav>
            <!-- Navigation links -->
            <ul>
                <li><a href="#home">Home</a></li>
                <li><a href="#mint">Mint Tokens</a></li>
                <li><a href="#about">About</a></li>
            </ul>
        </nav>
    </header>
    
    <main>
        <!-- Main content section -->
        <article id="home">
            <!-- Introduction article -->
            <h2>Introduction to Token Minting</h2>
            <p>This dApp allows users to mint their own tokens on the blockchain.</p>
        </article>
        
        <section id="mint">
            <!-- Token minting form section -->
            <h2>Mint Your Tokens</h2>
            <form action="#">
                <!-- Form for token minting -->
                <input type="email" placeholder="Enter your email">
                <input type="number" placeholder="Token amount">
                <button class="button" type="submit">Mint</button>
            </form>
        </section>
        
        <aside>
            <!-- Sidebar with additional information -->
            <h3>Learn More:</h3>
            <p>Explore more about blockchain technology.</p>
        </aside>
    </main>
    
    <footer>
        <!-- Footer with contact information -->
        <p>Contact us at <a href="mailto:hello@dProgrammingUniversity.com">hello@dProgrammingUniversity.com</a></p>
    </footer>
    
</body>
</html>

Enhance the Capstone Project with New Features from this Lesson:

Javascript Code:

// External JavaScript file for the global script

// Declare variables to track the total minted tokens and set a minting limit
let totalMintedTokens = 0;
const mintingLimit = 10000; // Set a limit for total tokens that can be minted

document.addEventListener('DOMContentLoaded', function() {
    const mintButton = document.querySelector('#mint button');
    const walletInput = document.querySelector('#walletAddress');
    const tokenInput = document.querySelector('#tokenAmount');

    mintButton.addEventListener('click', function() {
        let walletAddress = walletInput.value;
        let tokenAmount = parseInt(tokenInput.value);

        // Validation for wallet address and token amount
        if(walletAddress !== '' && !isNaN(tokenAmount) && tokenAmount > 0) {
            // Call function to update minted tokens and get result
            let mintResult = updateMintedTokens(tokenAmount);

            if(mintResult) {
                // Notify the user about the minting process
                alert(`Minting ${tokenAmount} tokens to wallet: ${walletAddress}`);
            }
        } else {
            // Alert for invalid input
            alert('Please enter a valid wallet address and a positive number of tokens to mint.');
        }
    });
});

// Function to update the total minted tokens
function updateMintedTokens(amount) {
    let successfullyMinted = false;

    // Use a for loop to add tokens to the total, respecting the minting limit
    for(let i = 0; i < amount; i++) {
        if (totalMintedTokens < mintingLimit) {
            totalMintedTokens++;
            successfullyMinted = true;
        } else {
            alert('Minting limit reached. No more tokens can be minted.');
            break; // Exit the loop if the minting limit is reached
        }
    }

    document.getElementById('totalMinted').textContent = `Total Minted: ${totalMintedTokens}`;
    return successfullyMinted;
}

To provide clarity on the changes made, here’s a summary highlighting the key modifications between the previous and the new lesson codes:

Changes Made in the New Lesson Code

  1. Introduction of a Minting Limit:
  • Previous Code: No limit on the number of tokens that could be minted.
  • New Code: Added a const mintingLimit = 10000; to set a maximum number of tokens that can be minted.
  1. Validation for Wallet Address and Token Amount:
  • Previous Code: Directly updated the total minted tokens without any validation.
  • New Code: Added an if/else statement to validate the wallet address and token amount to ensure they are not empty or invalid.
  1. Implementing a Loop for Token Minting:
  • Previous Code: The total minted tokens were incremented directly without a loop.
  • New Code: Added a for loop in the updateMintedTokens function to increment the total minted tokens while checking against the minting limit.
  1. Handling Minting Limit:
  • Previous Code: No handling of a situation where a minting limit is reached.
  • New Code: Incorporated an if condition inside the for loop to check if the minting limit is reached. If so, it alerts the user and stops further minting by breaking out of the loop.
  1. Conditional Alert for Successful Minting:
  • Previous Code: Displayed a minting alert irrespective of whether the minting action was successful or not.
  • New Code: Added a condition to display the minting alert only if the minting action was successful (if(mintResult)).

These changes incorporate essential programming concepts of conditional statements (if/else) and loops (for), which are crucial for JavaScript programming, especially in the context of Web3 development.

AFTER:

Your code may look something like the following after applying the above adjustment from this lesson:

Javascript Code:

// External JavaScript file for the global script

// Declare variables to track the total minted tokens and set a minting limit
let totalMintedTokens = 0;
const mintingLimit = 10000; // Set a limit for total tokens that can be minted

document.addEventListener('DOMContentLoaded', function() {
    const mintButton = document.querySelector('#mint button');
    const walletInput = document.querySelector('#walletAddress');
    const tokenInput = document.querySelector('#tokenAmount');

    mintButton.addEventListener('click', function() {
        let walletAddress = walletInput.value;
        let tokenAmount = parseInt(tokenInput.value);

        // Validation for wallet address and token amount
        if(walletAddress !== '' && !isNaN(tokenAmount) && tokenAmount > 0) {
            // Call function to update minted tokens and get result
            let mintResult = updateMintedTokens(tokenAmount);

            if(mintResult) {
                // Notify the user about the minting process
                alert(`Minting ${tokenAmount} tokens to wallet: ${walletAddress}`);
            }
        } else {
            // Alert for invalid input
            alert('Please enter a valid wallet address and a positive number of tokens to mint.');
        }
    });
});

// Function to update the total minted tokens
function updateMintedTokens(amount) {
    let successfullyMinted = false;

    // Use a for loop to add tokens to the total, respecting the minting limit
    for(let i = 0; i < amount; i++) {
        if (totalMintedTokens < mintingLimit) {
            totalMintedTokens++;
            successfullyMinted = true;
        } else {
            alert('Minting limit reached. No more tokens can be minted.');
            break; // Exit the loop if the minting limit is reached
        }
    }

    document.getElementById('totalMinted').textContent = `Total Minted: ${totalMintedTokens}`;
    return successfullyMinted;
}

CSS Code:

/* External CSS */
 
/* IMPORTS */
@import url('https://fonts.googleapis.com/css2?family=Roboto:wght@400;700&display=swap');
 
/* CSS Variables for consistent theming and easy maintenance */
:root {
    --font-family: 'Roboto', sans-serif;
    --bg-color: #f4f4f4;
    --bg-gradient: linear-gradient(to right, #630404, #e040fb, #6a027c);
    --nav-hover-bg-color: #630404;
    --nav-hover-text-color: #f3e40d;
    --text-color-white: #ffffff;
    --header-bg-color: #333;
    --header-text-color: white;
    --subtitle-text-color: #aaa;
    --paragraph-color: #cfbdbd;
    --main-border-color: #333;
    --article-border-color: grey;
    --form-border-color: #ddd;
    --input-border-color: #ccc;
    --button-hover-color: #f5f121;
    --invalid-input-border-color: red;
    --placeholder-color: #888;
    --info-text-color: #521f1f;
}
 
/* BODY */
body {
    font-family: var(--font-family);
    background-color: var(--bg-color);
    background: var(--bg-gradient);
}
 
/* NAVIGATION */
nav > ul > li {
    display: inline;
    margin-right: 20px;
    text-align: center;
    padding: 10px;
    flex: 1;
}
 
nav a:hover, nav a:focus {
    background-color: var(--nav-hover-bg-color);
    color: var(--nav-hover-text-color);
}
 
/* HYPERLINKS */
a[href^="#"] {
    text-decoration: none;
    color: var(--text-color-white);
}
 
/* HEADINGS */
header {
    background: var(--header-bg-color);
    color: var(--header-text-color);
    padding: 10px;
    text-align: center;
    display: flex;
    justify-content: space-between;
    align-items: center;
}
 
h1 {
    font-weight: 700;
    position: relative;
}
 
h1::after {
    content: '...the future of token minting';
    display: block;
    text-align: center;
    color: var(--subtitle-text-color);
    position: absolute;
    width: 100%;
    left: 0;
    top: 100%;
    font-size: 0.55em;
}
 
h1, h2, h3 {
    font-weight: 700;
}
 
h2 + p {
    color: var(--paragraph-color);
}
 
/* MAIN */
main {
    display: flex;
    flex-direction: row;
    gap: 10px;
}
 
/* ARTICLE */
article {
    margin-bottom: 15px;
    padding: 10px;
    border: 1px solid var(--article-border-color);
    flex: 1;
}
 
article p {
    margin-bottom: 20px;
    border: 1px solid var(--article-border-color);
    padding: 15px;
}
 
/* IDs */
#mint {
    background-color: #eaeaea;
    padding: 15px;
    margin-top: 10px;
}
 
#mint form {
    padding: 10px;
    border: 1px solid var(--form-border-color);
    margin-top: 10px;
    display: flex;
    flex-direction: column;
    gap: 10px;
}
 
#mint input,
#mint button {
    padding: 10px;
    margin-bottom: 10px;
    border: 1px solid var(--input-border-color);
    flex: 1;
}

#totalMinted {
    color: var(--info-text-color);
}
 
/* PARAGRAPH */
p {
    line-height: 3.5;
}
 
/* MEDIA QUERY */
@media (min-width: 768px) and (max-width: 1024px) {
    body {
        background: var(--bg-gradient);
    }
    main {
        flex-direction: row;
    }
}
 
@media (max-width: 767px) {
    nav ul {
        flex-direction: column;
    }
    .button {
        padding: 15px;
    }
}
 
/* ANIMATION AND TRANSITION */
@keyframes pulse {
    0% { transform: scale(1); }
    50% { transform: scale(1.1); }
    100% { transform: scale(1); }
}
 
.button {
    animation: pulse 2s infinite;
}
 
a {
    transition: color 0.5s ease;
}
 
a:hover {
    color: var(--button-hover-color);
}
 
@media (max-width: 600px) {
    .container {
        flex-direction: column;
    }
}
 
input:invalid {
    border-color: var(--invalid-input-border-color);
}
 
::placeholder {
    color: var(--placeholder-color);
    opacity: 1;
}

HTML Code:

<!DOCTYPE html> <!-- Defines document type and HTML version -->
<html lang="en"> <!-- Sets the language of the page -->
 
<head>
    <meta charset="UTF-8"> <!-- Sets character encoding for the document -->
    <meta name="viewport" content="width=device-width, initial-scale=1.0"> <!-- Ensures proper rendering on mobile devices -->
    <title>Token Minter dApp</title> <!-- Title of the webpage -->
    <link rel="stylesheet" href="/globalstyles.css"> <!-- Link to external CSS file -->
    <script src="/globalscript.js"></script> <!-- Link to external CSS file -->
</head>
 
<body>
    <header>
        <!-- Site header with navigation -->
        <h1>Token Minter dApp</h1>
        <nav>
            <!-- Navigation links -->
            <ul>
                <li><a href="#home">Home</a></li>
                <li><a href="#mint">Mint Tokens</a></li>
                <li><a href="#about">About</a></li>
            </ul>
        </nav>
    </header>
     
    <main>
        <!-- Main content section -->
        <article id="home">
            <!-- Introduction article -->
            <h2>Introduction to Token Minting</h2>
            <p>This dApp allows users to mint their own tokens on the blockchain.</p>
        </article>
         
        <section id="mint">
            <!-- Token minting form section -->
            <h2>Mint Your Tokens</h2>
            <form action="#">
                <!-- Form for token minting -->
                <input type="text" placeholder="Enter your wallet address" id="walletAddress">
                <input type="number" placeholder="Token amount" id="tokenAmount">
                <button class="button" type="button">Mint</button>
            </form>
            <p id="totalMinted">Total Minted: 0</p>
        </section>
         
        <aside>
            <!-- Sidebar with additional information -->
            <h3>Learn More:</h3>
            <p>Explore more about blockchain technology.</p>
        </aside>
    </main>
     
    <footer>
        <!-- Footer with contact information -->
        <p>Contact us at <a href="mailto:hello@dProgrammingUniversity.com">hello@dProgrammingUniversity.com</a></p>
    </footer>
</body>
</html>

Conclusion:

Understanding control flow in JavaScript is vital for creating interactive and responsive web applications.

With the knowledge of conditional statements and loops, you can significantly enhance the user experience of your web3 applications.

Resources & References:

To deepen your understanding of this lesson, you can explore the following resources:

  1. MDN Web Docs – JavaScript Basics reference
  2. W3Schools – JavaScript Tutorial
  3. Freecodecamp – JavaScript Handbook

These resources provide comprehensive guides and examples that will be invaluable as you learn and apply them in your journey of Web3 frontend development.


Support:

If you need help with this lesson, questions, suggestions and improvement. The best way to get help is to use the comment below:
1. First check existing comments if your questions have been answered before posting.
2. If no existing related question with an answer, then you can post a new one (kindly avoid duplicating previously asked and answered questions).

NOTE: This is the most recommended way of getting support directly from the instructor of this course. Posting on other platforms like Discord may get support from other community members and not from the course instructor directly.

Images|Videos|Links: To support your question with a screenshot, Github repo link or other media, kindly upload it somewhere online like Drive/Dropbox or Github (for codes) first, then post the link to it in your comment. Please do not upload media/codes directly, it may fail or cause your comment to be deleted.

Please ONLY post questions that are specific to this lesson not the entire course to ensure others can find it helpful. Each lesson allows comments relating to it ONLY. Off-lesson questions will be deleted even if they relate to this course as a whole but as long as they are not specific to this lesson, they are not allowed.

1 Comment
Collapse Comments
User Avatar Adeyanju Adelowokan June 24, 2024 at 6:04 pm

Good day Sir.
It seems all the quizzes in this section are for typescript and not javascript Sir.

Leave a Comment

By using this website you agree to accept our Privacy Policy and Terms & Conditions