skip to Main Content

I am trying few operations in java-script please help me to understand the below output or share the reference for reading.

console.log(1===1<3) //output False
console.log('1===1',typeof(1===1),1===1)
console.log('1<2',typeof(1<2),1<2)
console.log(1<2<3)//Outlet ture
console.log(true<3)

As per my understanding in the first output. Should be True but it is giving false.
if first output is false then the last two output will also be false. Please can you explain
Thanks

2

Answers


  1. Well the reason the first input returns false is the following :
    First the expression 1<3 is evaluated this results to the boolean value "true". The remaining expression is "1 === true" which is false as === strictly checks on the type. And true is of the type boolean whilst 1 is a number, resulting in the statement being false.

    The comparison is done first because it has a higher priority then the equality. Here is a list of operator priorities :

    enter image description here

    Login or Signup to reply.
  2. console.log(1===1<3) showing output False because of Precedence.

    The expression 1 === 1 < 3 is evaluated as follows: first, 1 < 3 is evaluated to true, since 1 is indeed less than 3. Then, 1 === true is evaluated. However, the === operator checks for both value and type equality. Since 1 is a number and true is a boolean, they are not of the same type, and the comparison returns false. Therefore, console.log(1 === 1 < 3) outputs false.

    w3school precedence order list

    Here is a visual demonstration for you to understand quickly how it works behind the scene.

    operator "<" will performed first because of its higher Precedence

    step 1- console.log(1===1<3) // calculation 1<3 output is "true"

    operator "===" checks for both value and type

    step 2- console.log(1=== true) // 1 is number and true is boolean means not same

    So the output is false.
    NB: console log is showing either true/false not 0/1 as a boolean. if it gives a boolean value for true as 1 then step 2 will show the expected values (1=== 1) //output "1" instead (1=== true) //output false.

    Reading Reference

    Comparison Operators "<" have higher precedence which is 9 than Assignment Operators "=" which is 2 in the Precedence list order. Read more here –
    W3school Precedence

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search