-1

Is there any shorter notation for the following test?

(typeof x != "undefined") ? x : y;

A kind of x || y but that operates on undefined only (and not falsey values)

Something like ?? of C#

frenchone
  • 1,547
  • 4
  • 19
  • 34
  • No, there is no such operator. – Pointy Jul 18 '18 at 14:17
  • 1
    Why? is it very important to shorten the code further? – mplungjan Jul 18 '18 at 14:18
  • 1
    || is not double pipe it is just logical "OR" – CharybdeBE Jul 18 '18 at 14:19
  • 1
    Define a function? `const foo = (x, y) => (typeof x != "undefined") ? x : y; ... foo(x, y)`. – Felix Kling Jul 18 '18 at 14:19
  • Unfortunately there is no shorter way to evaluate only undefined. – Emeeus Jul 18 '18 at 15:01
  • @mplungjan : the x || y notation is everywhere in your everyday javascript. But when people write it -most of the time- they really mean (typeof x != "undefined") ? x : y. And they get confused when it broke because of a falsey value (0 being one of those). People write x || y because they are lazy (or because they saw it elsewehere and thought they understand it while they ignore the side effects). This operator was missing in C# but was added because of popular demand. So I'm surprised there is not such notation in javascript – frenchone Jul 18 '18 at 15:03
  • I have yet to be surprised by a falsy value ;) since 1995 or so (Netscape) – mplungjan Jul 18 '18 at 17:29

2 Answers2

2

In fact the question should be rephrase as is there a null coalescing operator in javascript ?

And the answer is No, not now but it should be coming soon. See proposal here and implementation status here.

Is there a "null coalescing" operator in JavaScript?

frenchone
  • 1,547
  • 4
  • 19
  • 34
-1

If you are sure that undefined will never be overwritten, you can use something like x === undefined. This will return either true or false which you can test against.

Paul McBride
  • 318
  • 2
  • 9
  • 1
    (foo === undefined) will fail if foo is undefined. (but not if foo was set to be undefined foo = undefined) – frenchone Jul 18 '18 at 15:06