I don't understand the difference between this condition:
if ($("div")) { /* code */ }
and
if ($("div").length) { /* code */ }
What's the difference?
I don't understand the difference between this condition:
if ($("div")) { /* code */ }
and
if ($("div").length) { /* code */ }
What's the difference?
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.