-1

I was always using the || as a nullish coalescing sort of operator. Either A or B.

But if I do something like,

1  const a = null
2  const b = '123'
3
4  console.log(a || b) // 123
5  console.log(a) || console.log(b) // null, 123

Why are BOTH console logs executed on line 5? Even if a === null, shouldn't it just execute the first console log, and not look at console.log(b)?

Mike K
  • 4,270
  • 4
  • 25
  • 50
  • Why do you think the second `console.log` shouldn't be executed?! – deceze Nov 27 '19 at 12:49
  • Because it's either left side OR right side.. not both – Mike K Nov 27 '19 at 12:50
  • @MikeK — The value the whole expression evaluates as is the LHS or the RHS. The code still has to be evaluated to find out which of those it should be. – Quentin Nov 27 '19 at 12:51
  • It will have to *evaluate* both sides\* to be able to return a result… (\*if the LHS expression is falsey…) – deceze Nov 27 '19 at 12:51
  • The `A || B` operator always evaluates A first and only if A is falsy, then it evaluates B. `console.log()` always returns `undefined` which is a falsy value (just like `null`, https://developer.mozilla.org/en-US/docs/Glossary/Falsy) - regardless of the argument. That's why, after evaluating the first console log and receiving `undefined`, the second log always gets evaluated. – Szab Nov 27 '19 at 12:53
  • Are you alleging `console.log(null) === undefined`? – Mike K Nov 27 '19 at 12:54
  • Yes. Try it. `console.log(console.log(a))` → `null` `undefined` – deceze Nov 27 '19 at 12:54
  • So the misconception on my part here is that even though `a` is null or not, `console.log` will print it, however return `undefined` regardless? – Mike K Nov 27 '19 at 12:57
  • 1
    Yes. The function call evaluates to whatever value the function returns. `console.log` doesn't return anything, because, why would it, what's there to return for it? – deceze Nov 27 '19 at 12:58

1 Answers1

4
  1. The left side is evaluated.
  2. console.log(a) returns undefined (because that function always returns undefined)
  3. Since the LHS evaluated as a falsy value: The right side is evaluated.

The value of a is irrelevant as that isn't what is on the LHS.

Quentin
  • 800,325
  • 104
  • 1,079
  • 1,205