-2

How it's work for example;

let x;
console.log(x || 2); // 2 

if

let x = 4;
console.log(x || 2); // 4

if

let x = 5;
let y = 7;
console.log( y || x || 2);

it's mean that console.log() write first value that is true ?

Walter White
  • 976
  • 4
  • 12
  • 29
  • 4
    No, it's how `||` works. – ibrahim mahrir Oct 23 '17 at 14:06
  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_Operators – Pointy Oct 23 '17 at 14:06
  • It has nothing to do with `console.log()`. The `||` operator simply returns the value of the left operand if it's truthy and the value of the right operand otherwise. `console.log()` simply receives and logs the returned value. – Lennholm Oct 23 '17 at 14:08
  • 1
    I'm not sure I'd call that the correct duplication target since the misunderstanding is over short circuiting, not if `0 == false`. – Mike Cluck Oct 23 '17 at 14:14

2 Answers2

5

What you're seeing isn't related to console.log. It's called short circuiting.

When comparing values with ||, it will always return the first truthy value. If no truthy values are present, it will return the last value being compared.

let a = false || true;
let b = false || null || 'b';
let c = undefined || !a || 10;
let d = undefined || false || null; // no truthy values

console.log(a); // true
console.log(b); // 'b'
console.log(c); // 10
console.log(d); // null
Mike Cluck
  • 31,869
  • 13
  • 80
  • 91
1
let x = 5;
let y = 7;
console.log( y || x || 2); //return 7

expr1 || expr2 Returns expr1 if it can be converted to true; otherwise, returns expr2. Thus, when used with Boolean values, || returns true if either operand is true.

Documentation: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_Operators

Damien
  • 1,582
  • 1
  • 13
  • 24