This is happening because the jQuery object is probably empty.
Let's just go through your code step by step:
var varId = $("#someInputId");
So after this, you have a jQuery object referenced by varId. Keep in mind, this is a jQuery object, regardless of the number of elements that were returned. Now you do this:
if (typeof varId !== "undefined" && varId.val().length == 0)
First thing here, and not sure if this was just a typo in the question, !== should be !=.
Anyway, consider the typeof varId != "undefined" part of the condition. This will return true, since varId is an object and is not undefined. Since this is true, the condition evaluation moves on to the next part. So while evaluating varId.val().length == 0, you're getting the error Uncaught TypeError: Cannot read property 'length' of undefined. In order for something to have the length property, it must be a string or an array, and val() in jQuery returns a string, or an array in the case of a multiple select input. However, if the jQuery object is empty, then val() will return undefined, which doesn't have a length property.
So basically, you can rewrite the expression as follows:
if ( varId.length && varId.val().length === 0 ) {
// Do something
}
underfined? Did you meanundefined?val()and what is$