Why a for loop won't work inside the button click event?

Why does a for loop not run inside a button click event? Here’s the code


What i want to achieve is after i enter a number in the input field and click the submit button, the for loop should run and print all the numbers to the console. How can i achieve this?

@Harshit_Badolla you are very nearly right here. The main problem is that you have put the line let num = Number(input.value); in the global scope, so it runs immediately, as soon as the page loads. Given that there is nothing in the input when the page first loads, num will always be nothing, so you won’t get anything printed when you click the button.

You should put that line inside the click handler so that num will be equal to the input value when you click the button, not the input value when the page first loads.

Another small tip — if you want it to print all the way up to the num value, not the number below it, you’ll want to change the for loop exit condition from i < num to i <= num.

1 Like

You sir, are a legend. Thanks for solving all my doubts.

You are most welcome :wink: