0

What is the purpose of the following line of JavaScript?

for (p in d) d.hasOwnProperty(p) && h.push([p, d[p]]);

From what I can see it doesn't change nothing. Does it mean: If d has the property p AND p and d[p] can be pushed onto h than the expression is true? Thus, the h.push will never happen if d does not have the property p.

This is exactly why I hate concise code.

Torra
  • 1,182
  • 5
  • 15
  • 23

2 Answers2

1

The idea is that when using &&, the left part is evaluated first. If, and only if, its return value is true, is the right part evaluated at all.

So, for each iteration, d.hasOwnProperty(p) is evaluated first. If the result is true, then h.push([p, d[p]]) is evaluated.

Eran Boudjnah
  • 1,228
  • 20
  • 22
0

It's a shortcut of

for (p in d) if (d.hasOwnProperty(p)) h.push([p, d[p]]);
Oriol
  • 274,082
  • 63
  • 437
  • 513