Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

JS Why Won't This Console.Log Evaluate Properly?

let a=3, b=4, c=5;
console.log(`b > a ` + b>a);
console.log(`c < a ` + c<a);
console.log(`!(a<b)` + !(a<b));

Why is it that the last line is executed with the proper string + the result, but the other two don’t include the string?

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

It’s because of operator precedence. Arithmetic operators have higher precedence than comparison operators (so you can write things like if (x + y > z)), so

console.log(`b > a ` + b>a);

is equivalent to

console.log((`b > a ` + b) > a);

This logs the result of the comparison between 'b > a 4' and 3.

You want to concatenate the result of the comparison, so you have to write

console.log(`b > a ` + (b > a));

to override the default precedence.

Your last example works as intended because !(a<b) groups the comparison together as a single expression, similar to (b > a) in my rewrite.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading