DEV Community

SEENUVASAN P
SEENUVASAN P

Posted on

Day 7: My JavaScript Learning Journey: while Loop, parseInt, and isNaN

Today I worked on a small but fun project — a Multiplication Table Generator — and learned some important JavaScript concepts: while loops, parseInt, and isNaN.

Here’s what I built and what I learned along the way!
Project: Multiplication Table Generator

The goal of the project was simple:

The user enters a number, clicks a button, and sees that number's multiplication table from 1 to 10.
Enter fullscreen mode Exit fullscreen mode

Html code:


<input id="generate" type="text" placeholder="type any number">
<button onclick="tables()">result</button>
<div class="result"></div>
Enter fullscreen mode Exit fullscreen mode

And the JavaScript logic:

function tables() {
    let number = parseInt(document.querySelector('#generate').value);
    if (isNaN(number)) {
        result = 'not a number';
    } else {
        let i = 1;
        let n = number;
        while (i <= 10) {
            result += `${i} * ${n} = ${i * n}\n`;
            i++;
        }
    }
    document.querySelector('.result').innerHTML = result;
}
Enter fullscreen mode Exit fullscreen mode

What I Learned

parseInt()

This function converts a string into an integer. For example, if the user types "5" in the input box, parseInt("5") converts it to the number 5.

isNaN()

This checks if something is NOT a number. If the input cannot be converted to a number, isNaN() returns true, and we display a message like "not a number".

while Loop

Instead of repeating the same line 10 times, I used a while loop:

while (i <= 10) {
    // generate table line by line
}
Enter fullscreen mode Exit fullscreen mode

This helped generate the table from 1 to 10 dynamically.

Top comments (0)