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

Why is my non-empty string evaluating to false?

var myString = "apples";
myString==true;

When I run this code in the JS console, it evaluates to false. I don't get it. I know empty strings are false, but not non-empty strings.

2 Answers

If you want to get true, you could write something like this:

var myString = "apples";

// All the following are true
myString != true;
myString ==  "apples";

When you write "myString == true;" you are comparing a literal string value with a boolean value, "apples" with true. This is like comparing apple to oranges (sorry, I had to say it :P) Since the values are not the same you are getting false.

I think Erik hit the nail on the head. Since "apples" and "true" don't match you get false. If you put myString in an if statement it would evaluate to "true" and execute the if statement.