1

I don't understand the difference between this condition:

if ($("div")) { /* code */ }

and

if ($("div").length) { /* code */ }

What's the difference?

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
Andy88
  • 647
  • 2
  • 9
  • 21

1 Answers1

2

The first if condition is incorrect as $('div') returns an object. Type coercion to a boolean from an object - even an empty one - will always equate to true.

The second condition is checking the length property of the object, which is an integer. Type coercion on that type will be false if the value is 0 and true for anything else, either positive or negative, hence it works.

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339