Use Button value as int

Hello.

Im using html Button value=“1”
This value returns a string. So how is it possible that I can use it in calculations? E.g. 1 + Button.value returns 2.

Is it safe to use it as int even though it returns a string? Or will it give unwanted results in the future?

Bless

You can force the value to an integer by placing it within Number() (Note the capital N).

Number(Button.value+1)

V/r,

^ _ ^

1 Like

Hey. Its working already without any other actions. Thats why im worried

That is odd. Especially if you are using quotes to delineate the value. I mean, if you were using value=1 instead of value=“1”, I could see it maybe working. Maybe. But working when a string is passed, without any alteration?

V/r,

^ _ ^

You should use parseInt() if you want to be sure it’s typecasted to an int.

let value = parseInt(button.value, 10)

Hey. Its working already without any other actions. Thats why im worried

JavaScript is dynamically typed.

1 Like

Implicit coercion is tricky business I try to avoid, even if using explicit coercion results in more verbose code.

The reason that “works” is because JavaScript “+” is “left to right”. If what is seen first is a number, it makes whatever follows it a number (if it can). If what it sees first is a string, it makes whatever follows it a string.

1 + “1” // 2
“1” + 1 // 11

IMHO, whenever there may be some doubt about a values type, if you want a string, cast to a string, if you want an integer, cast to an integer.

1 Like

In my case the button will hold the value of “-1” or “+1”.
Myvar = 6

Then, Myvar += Button.value.

Based on what you say about Left to right… This should always work then?, because Button.value will always be on the right side.

Can I read more about this somewhere?

Take care

Values in forms are always strings, no matter what you do, no matter which language (or at least in the languages I know of; JavaScript, php, python, java, golang).

In Javascript to do calculations with a value from a form you need parseInt as @mawburn already suggested.

Also, the second argument to parseInt must be 10, otherwise you get very weird results.

1 Like

In my case the button will hold the value of “-1” or “+1”.

For this case, I would use 2 different listeners which incremented x++ / x+=y or decremented x-- / x-=y the given value, instead of relying on storing your data in the dom.

You could try searching for “type coercion”, “type juggling” and “truthy” to get some insight.

As has been suggested, it is much better to not bother relying on implicit type coercion just to save a few characters in the code.

Although different languages may have some “rules” in common, they also have others that are different. It is a good thing to be aware of, but relying on it could lead to difficult to solve bugs.

3 Likes

Thank you all. The answers have helped me. I appreciate it

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.