DEV Community

Discussion on: Number Generator With JS

Collapse
 
oskargrosser profile image
Oskar Grosser

As refreshing as it was to see a switch-block in JS, I do agree that a lookup table is likely a better fit in JS, simply because it is easy to implement and understand. Though I would have the numbers be generated by the lookup functions, instead of just checking whether they are of a certain type.
Also, ECrelier, your function names seem misleading. For example, "real" returns true for every number, but "even" and "odd" return true when a number is not even or odd, respectively. I would pass a pre-increment (++contador) instead of a post-increment.

I did not know that elements with an ID are objects on the global object, awesome!
Now that we are already trying to skip looking through the document, we can wrap the <input>s and the <button> in a <form>. That way, we can access all the named values like so: form.name.value. This even works for radio-groups!

And while we are using a <form> already, we may even use an <output> as well. It is an aria-live region by default, so it is giving live feedback from the result of our <form> to the user. This is good for accessibility reasons!

When using a <form>, we can also make the "total" number-input required. That way, our form-element is only submitted once all required input-fields are filled out validly.
Note: By default, a form-submission is a GET-request to the current URL. To prevent this, use event.preventDefault().

And, ECrelier, to your argument that we should not use a <form>, here is my opinion:

  • The WAI-ARIA specification does explicitely allow the use of client-sided form-evalutations, especially if the user is informed of such.
  • The HTML specification does not specify as to how a submission has to be processed by developers, only how it should be processed by default.
  • And MDN (though only a community-created wiki) states that web forms can be "used on the client-side".

In my opinion, we are filling out a form, and request it to be processed (one may call this "submitting"). This "submission" is just handled client-sided, instead of server-sided.
As I said, this is just my opinion and interpretation of the specifications, and everyone may have their own regarding this topic. I just hope that I changed your mind from "no, never use it like this" to "okay, if you want to, you can do so".

I also did not know that you can just assign an array to .innerHTML, .innerText and .textContent! I would have used Array.join() to transform it to a string before assigning it. But yours is cleaner and easier to read, will definitely use it in the future!

Here is a pen with how I would do it, plus comments to your version:
codepen.io/oskargrosser/pen/mdMaGxo

Collapse
 
walternascimentobarroso profile image
Walter Nascimento

Hi Oskar, thanks for contributing, I really enjoyed the comment, I'll enjoy and improve my code even more, thanks ;)