Jump to content

? What does this do --> return (controlName.attr('type') || controlName[0].tagName).toLowerCase();


pmingione

Recommended Posts

Hi All, I've recently encountered this line of javaScript code. return (controlName.attr('type') || controlName[0].tagName).toLowerCase(); I haven't ever seen this structure before. Can anybody explain it to me. I am confused as to what the or ( || ) is doing. One of the two strings ( either controlName.attr('type') or controlName[0].tagName) is being processed by the toLowerCase() library function. But I am unsure of what the procedure is. If the object has both a type attribute and a tag name then what is actually being returned? Thanks PMingione

Link to comment
Share on other sites

The || operator means "or." If the object on the left side of || has a value or evaluates to TRUE, then that object will be returned. Otherwise, the object on the right will be evaluated the same way. In this case, if the object has a type attribute, then the value of that attribute will be returned in lower case. If it doesn't, then the tagName will be returned in lower case. I think it's really testing whether controlName is a single element or a collection of elements, and I guess it's working with form inputs. If the object is just one input, it will have a type. If it's a collection, the test returns the tagName of the first element in the collection. So maybe controlName was constructed by getting the child elements of something like a form?

Edited by Deirdre's Dad
Link to comment
Share on other sites

this is an example of basic boolean (true/false, on/off) logic in action. basically, it is going to attempt to evaluate the first expression

controlName.attr("type')

assuming that controlName.attr('type') returns any sort of truthy value, then that value will be used. if not, then the next expression

controlName[0].tagName

will be evaluated in the same way. whichever expression evaluate as thruthy first, will have toLowerCase() called upon it and then returned.

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...