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(`${me.name} is ${me.age}.`);
me.age = me.age+1
console.log(`${me.name} is ${me.age}.`);
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
Depending on the context +valuecoercion 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.