What is advantage for use .length with function

For a map example?

 if ( $('#mapBox').length ){
//google map goes here

Saw this one many times? As i know .length give back a number? What is advatage to use this as call a google map function in a js file?


so in your code above, $("#mapBox").length will do two things: first, the jQuery object will take that selector, and create a nodeList of objects that match the selector. If it were a class, or a tagName, then there could be zero or more; in the case of an ID, in an ideal world, you would have zero or one.

Next, passing back that nodeList (which is basically an Array), we can use .length to check – if $("#mapBox") didn’t match any elements, then $("#mapBox").length will equal zero, which is considered a ‘falsy’ value. If it did match any, then length is now a non-zero value, and we pass into our if statement.

1 Like