DEV Community

Moszio
Moszio

Posted on

parseInt()!

Introduction

The reason behind choosing this particular topic? As a student at Flatiron School we go through many challenges and many time you come across a challenge that requires you to google. I still have a lot to improve on my googling skills. See here comes in the choice of my topic. I just could not find the answer to this very simple question. I tried so many ways and even though you can find some answer they just seemed way to difficult.

"The challenge"
In that particular challenge you had to add a vote based on the value of your input field to your total vote count.

   <h4>Total Votes: <span id="vote-count">Character's Votes</span></h4>;
        <form id="votes-form">;
          <input type="text" placeholder="Enter Votes" id="votes" name="votes" />;
          <input type="submit" value="Add Votes" />;
        </form>;
Enter fullscreen mode Exit fullscreen mode

It is nothing too complicated right? Well the answer was not so straight forward. Since the input is a string it will not be able to cumulate your votes.

This is when parseInt() comes useful.

 let count = 0;
 count =  parseInt(input.value) + count;
   characterVote.textContent = count;
Enter fullscreen mode Exit fullscreen mode

This function will return an integer from the string argument and from now it will be able to cumulate your total count.

Hope this was useful! Feel free to reach out if you have or had the same struggle with parseInt() and strings :D.

Also here is a link to more information about parseInt():

MDN web docs_:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt

Top comments (2)

Collapse
 
besworks profile image
Besworks • Edited

In some cases it might be preferable to use Number(value) instead of parseInt(value). For instance, when used with an empty string, parseInt will return NaN but Number will return 0.

Or maybe you have a mix of integers and floats in your input strings, Number will return the appropriate type, whereas parseInt will only return the whole digits up to the decimal point and drop the remainder without any rounding.

Collapse
 
andor profile image
Moszio

Good to know!