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 trialJerry Liu
Courses Plus Student 1,233 PointsWhy is this condition always true?
function arrayCounter (my_var) {
if (typeof my_var === ('number'|'string'|'undefined')) return 0;
else return my_var.length;
}
arrayCounter();
1 Answer
Dino Paškvan
Courses Plus Student 44,108 PointsThat condition is not always true. In fact, it's never true. The else
statement will always get executed. A single pipe character (|
) is not the logical or operator. It's a bitwise or operator, and as such, it only works on numbers (and not in the way you'd expect a logical or to work).
So, this part of the code: ('number'|'string'|'undefined')
will always return 0
, because you are trying to use bitwise operators on a string. The typeof
operator will never return 0
, and because of that, the if
condition will never pass. Instead, the code in the else
block is executed.
If you want to understand how the logical or works, take a look at this thread.