Giving unexpected answer Javascript

114 views Asked by At

 const phoneNumber =345
 console.log(phoneNumber === 345) //output is true
 console.log (
      phoneNumber ==(123||345||567),
    );  //output is false

Or operator is not showing the proper output , it should show true instead of showing false in second console

4

There are 4 answers

5
Md Nazmul Hossain On

The behavior you're observing is due to how the logical OR (||) operator works in JavaScript, not due to a malfunction or bug.

In JavaScript, the logical OR (||) operator returns the first truthy operand it encounters, or the last operand if none are truthy. When used in the context of your example, it doesn't compare phoneNumber to each of the three numbers (123, 345, 567) individually. Instead, it evaluates the expression (123 || 345 || 567) first, and then compares the result of that expression to phoneNumber.

Let's break down what happens in the second console.log statement:

The expression inside the parentheses is evaluated from left to right: (123 || 345 || 567). Since 123 is truthy (in JavaScript, all numbers other than 0 are considered truthy), the OR operation stops at the first operand (123), and the entire expression evaluates to 123. Therefore, the comparison effectively becomes 345 == 123. Since 345 does not equal 123, the comparison returns false. This is why the output is false instead of true. If you want to check whether phoneNumber matches any of the three numbers, you need to compare them individually, like this:

console.log(phoneNumber === 123 || phoneNumber === 345 || phoneNumber === 567);

This approach compares phoneNumber to each of the three numbers separately and uses the OR operator to check if any of those comparisons are true. If phoneNumber matches any of the specified numbers, the result will be true.

0
kiuQ On

This related to the javascript syntax. In JavaScript, the || operator returns the first truthy value it encounters, or the last value if none are truthy. Since 123 is the first value that js think it is true. So it will always return 123.

You can just split it into 3 conditions.

if (phoneNumber == 123 || phoneNumber == 345 || phoneNumber == 567) {
  //...
}
0
Hamza Anis On

const boolean = phoneNumber === 123 || phoneNumber === 345 || phoneNumber === 567 try like this then

console.log(boolean)

1
Saurabh Sahni On

The behavior you are observing is due to the way the logical OR (||) operator works in JavaScript.

In the second console.log statement, the expression (123 || 345 || 567) is evaluated using the logical OR operator. The logical OR operator returns the first truthy value in the sequence, or the last value if none are truthy.

If you want to check if phoneNumber is equal to any of the values 123, 345, or 567, you should use multiple equality checks(other comments) or an array includes method:

const phoneNumber =345 

// using array includes
console.log([123, 345, 567].includes(phoneNumber));