0

I was checking the code in a library and I found this little piece:

if (typeof options === 'function') (callback = options), (options = {});

Is this just another way of writing

if (typeof options == 'function) {
  callback = options;
  options = {};
} 

?

It's just that I've never seen an if statement declared like this and wondered if this is accepted, maybe, only in Javascript?

user3063909
  • 333
  • 3
  • 12
  • 1
    Yes, that is correct – adiga Mar 04 '20 at 09:16
  • The body of an `if` statement has to be a single statement (using a *block statement* (`{...}`) allows you to write multiple statements). In this case it is an *expression statement*. `(callback = options), (options = {})` is a single expression, using the [comma](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comma_Operator) and [assignment](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Assignment_Operators) operators. It's not a special version of the `if` statement, it's just (ab)using the language constructs. – Felix Kling Mar 04 '20 at 09:16
  • Just keep the style like in the latter example, the first snippet is not readable, though it's valid JS. – Teemu Mar 04 '20 at 09:16
  • 3
    It's correct, as in, *it works*, but I'd also call that a terrible abuse bordering on needless obfuscation. – deceze Mar 04 '20 at 09:16

0 Answers0