How to increase age by one with JS

I tried to increase the age by one by adding 1 , please see below, I wanted to get to 39 yet I keep getting 391. How do I make it right?
“Mike is 38.”“Mike is 381.”

let me = {
  name: "Mike",
  age: "38",
  location: "Niagara Falls"

console.log(`${} is ${me.age}.`);

me.age = me.age+1
console.log(`${} is ${me.age}.`);


me.age = +me.age+1
1 Like

Thanks jenovs, it works!

age is a string, you need to convert it to a number before being able to do mathematical operations on it

Thanks. I used me.age=+me.age+1 to get the 38.

Right. The way that works is that sticking + in front implicitly casts the string “38” to the number 38.

That’s a hacky implicit cast that is best avoided.

1 Like

Just as a further information thing…
A side effect of what is happening here is that the type of age is changed. Originally it is a string, but if you save the number 39 into it (without casting it to a string first) then the type of data contained in me.age changes. In your use case this may be perfectly fine, but in complex code it’s often pretty important to know what type of data you’re working with.

Hi what’s that mean by “hacky implicit” I ran into a challenge ,and could not get the same output with the instructor . That’s why I posted a question because I need help and I want the genius knowledge. I will appreciate any info. Thanks

B. DiCarlo

Thank you. Good to know and I will keep that in mine.

Depending on the context +value coercion can be more or less problematic. Not sure if I would call it hacky but personally I don’t like it all that much.

One gripe I do have with it, beyond the more obvious of possibly being a bit confusing in certain contexts and it being an implicit conversion, is the lack of easy code scannability and having a good search term. Checking that a value is correctly converted somewhere in thousands of lines of code is less obvious with the implicit +value coercion. I would suggest using explicit conversion, e.g. using Number() or one of the parse methods can increase the code legibility.

I’m not sure why it seems to a gained so much popularity, I never really saw many benefits from using it. And I know I have read code where I would have preferred the explicit version was used as it just made it harder to spot the conversion.


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