0

I had a question regarding the || operator in javascript. To my understanding it can be used as either an 'OR' operator, or a null coalescing operator.

My question is, can I use if statements in conjunction with the || null coalescing operator? For example,

if (x=y){
alert("Yup");
}||if (x=0){
alert("Nope);
}

Thanks in advance.

user2864740
  • 60,010
  • 15
  • 145
  • 220

1 Answers1

4

No. Just use else

The JavaScript grammar distinguishes between statements like

if (condition) statement else statement

and expressions like

expr || expr

A statement can contain expressions with few restrictions° via the ExpressionStatement production, but expressions can only contain statements in a very limited way°°.

So

{statement} || {statement}

is neither a valid statement nor a valid expression because the JavaScript parser sees the || where it expects a statement to appear and reports a parse error.


Second, || is not really "null-coalescing". To see why, consider

alert(false || null)  // alerts "null" not "false"
alert(0     || null)  // alerts "null" not "0"
alert(""    || null)  // alerts "null" not the empty string
alert((0/0) || null)  // alerts "null" not "NaN"

Since the left-hand-sides of the || are falsey the null is given preference which is not what you would expect if only nulls were coalesced.


° - the { key: value } object constructor is ambiguous with blocks, and named function expressions are ambiguous with function declarations so both are banned unless parenthesized.

°° - a function expression like function () { ... } can contain statements in its body.

Community
  • 1
  • 1
Mike Samuel
  • 118,113
  • 30
  • 216
  • 245