Typically in a case where jQuery fails to find matching elements using its selector the default value is never an exception but rather a lack of action.
My understanding is this is done by design to ensure that the lack of an element does not result in an error condition. However I have found that jQuery.val() does not exhibit this same behaviour. If a selected element does not exist jQuery.val() will return undefined rather than an empty string (which in keeping with the remainder of the framework I would have expected).
So why is jQuery.val() an exception to the rest of the framework and what would be the best way to change this behaviour?
The key here is chainability of jQuery methods. A jQuery method doesn’t return
undefinedwhen a selector doesn’t match anything because it would break the chain. Consider:If the selector that doesn’t match anything would return
undefinedit would break the chain sinceundefineddoesn’t have any methods of its own. Now every method is executed (and do nothing) whether or not the element is found..val()on the other hand is different since it’s purpose is to return the value of an element. It doesn’t chain at all unlike many other jQuery methods, because a method has to return a jQuery object for it to be able to chain. For example,$( '#foo' ).val().addClass( 'bar' )does not work regardless of whether the element#fooexists or not.In this light having
.val()return an empty string would not make it any more in line with chainable methods, since no other method returns an empty string when the element isn’t found either, and returning undefined does not break chainability since the method doesn’t chain in the first place.(By the way, the same is true for every method that returns a value, like
.css()and.data().)Usually it’s more useful to know whether the value of an element is empty or whether the element doesn’t exist at all, but if you prefer to always get a string back you can add a method of your own: