I am trying to write a Javascript function that returns a single element given the name. I found this question and modified the answer to use the ternary operator.
function getField(fieldName)
{
var elements = document.getElementsByName(fieldName);
return elements.length && elements.legth > 0 ? elements[0] : null;
}
My question is about the case where document.getElementsByName(fieldName)
doesn't find any matches. Does it return undefined
or 0
? When I output elements.length
as an alert message, the value in the alert is 0
but the console Chrome's DevTools says undefined
. When I call console.log(elements.length)
from the console, it ouputs 0
and undefined
.
I know that my function handles either case, but what am I missing here? What is Javascript actually doing?
Thanks in advance for helping me understand this.
EDIT: Sorry for posting a picture instead of actual code and thanks for the syntax clarification.