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 trialAlexander Kruglov
3,148 PointsCompare function working not as expected
function compare (a,b) { console.log(a+"<"+b+" "+a<b); }
compare('a','b');
What do I expect: a<b true What do I get: true
Why doesn't it output the first half of the argument? I don't get it.
1 Answer
bothxp
16,510 PointsSo you are doing:
console.log('a' + "<" + 'b' + " " + 'a' < 'b');
Take a look at: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence
The additions happen first. So you are actually getting
('a' + "<" + 'b' + " " + 'a') < 'b'
To get the result that you are expecting you'll need to put some ( ) around less than check
console.log('a' + "<" + 'b' + " " + ('a' < 'b'));
So that would be:
function compare (a,b) {
console.log(a + "<" + b + " " + (a < b));
}
compare('a','b');
Alexander Kruglov
3,148 PointsAlexander Kruglov
3,148 PointsThank you, now I understand.