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

Logical OR condition interpretation

Using JavaScript code below it should print the same result, but it doesn’t. Using logical OR for both of the statements, the interpreter -according to my experience- it should return immediately after checking the 1st condition as soon as it finds it true. This is not the case in the example below.

Can someone explain this? Y works as expected but X does not. So, how JavaScript interpreter "decode" the X statement?

function test() {
  var x = 5 || true ? 100 : 1000;
  var y = 5 || (true ? 100 : 1000);

  console.log(x); //returns 100
  console.log(y); //returns 5
};

test();

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

>Solution :

it will run as (5 || true) ? 100 : 1000;

you can find here that operator || has precedence greater than conditional ?.

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