Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript JavaScript Basics (Retired) Making Decisions with Conditional Statements Build a Random Number Guessing Game

Matthew Beiswenger
Matthew Beiswenger
6,814 Points

== vs. parseInt

In this video, Dave uses parseInt to convert a string to an integer so it can be compared to another integer. Can't the == operator also be used since it will automatically convert an string to an integer? Or is it just best practice to use parseInt to avoid confusion with things like "" == 0?

1 Answer

andren
andren
28,558 Points

You are correct, == could be used instead. But nowadays use of == is generally discouraged. It can easily lead to unexpected and buggy behavior exactly like you demonstrate with your "" == 0 example.

And beyond that it's also in most cases a bad idea to store pure numbers in a string. As it can lead to buggy behavior if said number ever ends up being used in a mathematical operation or something like that.

If you use the + operator on a number stored in a string for example then it will be concatenated (glued together) with the other thing you specify instead of having addition performed on it. "5" + 5 equals "55" for example. Potentially running into unexpected behavior like that is something you should go out of your way to avoid.