2

We minify our code with uglify-js and I have spotted a strange format which is used when compiling the following javascript:

console.debug(`[NotificationOpenedHandler] Received additionalData:`, data);
if(data.type && data.id) {
// more code...

This will be turned into the following:

if (console.debug(`[NotificationOpenedHandler] Received additionalData:`, e), e.type && e.id) {

First I thought its some compiler error, likely generated by uglify-js when trying to minimize the code but after testing it seems (true, true & false) it's a valid expression (No syntax error).

The value of the first expression doesn't matter so

(true, true & false) // -> false
(true, true & true) // -> true
(false, true & false) // -> false
(false, true & true) // -> true

My question, what does this expression mean?

NoNameProvided
  • 8,608
  • 9
  • 40
  • 68
  • 4
    [Logical AND](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_Operators#Logical_AND_()) and [When is the comma operator useful?](//stackoverflow.com/q/9579546) – Tushar Jan 27 '17 at 10:02
  • 6
    [Comma operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comma_Operator). – Felix Kling Jan 27 '17 at 10:02
  • return (x += 1, x); // the same as return ++x; process x = x +1 then return. comma operator in your case is processing before returning – Ihtsham Minhas Jan 27 '17 at 10:12
  • Another possible dup-target: [Why does \[5,6,8,7\]\[1,2\] = 8 in Javascript](//stackoverflow.com/q/7421013) – Makyen Jan 28 '17 at 06:19

1 Answers1

3

My question, what does this expression mean?

From https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comma_Operator

The comma operator evaluates each of its operands (from left to right) and returns the value of the last operand (right most one).

Example:

if (y = f(x), y > x) {
    // do something ...
}

This executes first the y = f(x) which sets up a value for y (that depends on x). Then checks if y > x. If True then do something, otherwise do nothing. It is the same as:

y = f(x);
if (y > x) {
    // do something ...
}

In your examples:

(true, true & false)
// process `true` (does nothing)
// returns the result of `true & false` => false

(true, true & true)
// process `true` (does nothing)
// returns the result of `true & true` => true

(false, true & false)
// process `false` (does nothing)
// returns the result of `true & false` => false

(false, true & true)
// process `false` (does nothing)
// returns the result of `true & true` => true

Further examples:

(true, true, true, false) // returns false
(false, false, false, true) // returns true

So, in your application code:

if (console.debug(`[NotificationOpenedHandler] Received additionalData:`, e), e.type && e.id) {

Is the same as:

console.debug(`[NotificationOpenedHandler] Received additionalData:`, data);
if(data.type && data.id) {
Marc Compte
  • 4,579
  • 2
  • 16
  • 22