Pipeline operators and variables

I’m running an if else statement, with a variable defined with pipeline operators. When let chosenNumber = 2 I get ‘wrong number’, even though the let number = 1 or 2.

function findNumber() {
  let number = 1 || 2
  let chosenNumber = 2;

  if (chosenNumber == number)  {
    console.log('correct!')
  } else {
    console.log('wrong number')
  }

It’s not a pipeline operator, it’s a boolean OR (1 OR 2). It’s one OR the other.

And understand that [from what you’ve written here] you’re actually expecting number to be both 1 and 2 at the same time – is an incorrect assumption, the language cannot do this. It would need to randomly assign one of two values to a variable. You need to be more precise. What you’re trying to do doesn’t make sense. I understand what you thought it did & why, but it is wholly wrong I’m afraid.

The way you are using it causes a short-circuit: it is the same as writing

let number = 1;
if (number === true) {
  number = 1;
} else {
  number = 2;
}

"If the value on the left of the OR is true, assign that to number, otherwise assign the value on the right to number".

1 will always evaluate to true, so number is assigned 1.

Normally if you have construct like this you should use function:

const checkNumber = (num) => (num === 1 || num === 2);
let chosenNumber = 2;

if (checkNumber(chosenNumber))  {
  console.log('correct!')
} else {
  console.log('wrong number')
}

Thanks for the explanation, I think I get it now :slight_smile: