Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

returning with &&

What does it mean to return a value with &&?

else if (document.defaultView && document.defaultView.getComputedStyle) {      // It uses the traditional ' text-align' style of rule writing,      // instead of textAlign     name = name.replace(/([A-Z]) /g, " -$1" );     name = name.toLowerCase();     // Get the style object and get the value of the property (if it exists)     var s = document.defaultView.getComputedStyle(elem, " ") ;     return s && s.getPropertyValue(name) ; 
like image 268
steve Avatar asked Dec 20 '10 13:12

steve


People also ask

What do you mean by returning?

to go or come back, as to a former place, position, or state: to return from abroad;to return to public office;to return to work. to revert to a former owner: The money I gave him returns to me in the event of his death. to revert or recur, as in thought, discourse, etc.: He returned to his story.


2 Answers

return a && b means "return a if a is falsy, return b if a is truthy".

It is equivalent to

if (a) return b; else return a; 
like image 92
dheerosaur Avatar answered Sep 18 '22 10:09

dheerosaur


The logical AND operator, &&, works similarly. If the first object is falsy, it returns that object. If it is truthy, it returns the second object. (from https://www.nfriedly.com/techblog/2009/07/advanced-javascript-operators-and-truthy-falsy/).

Interesting stuff!

EDIT: So, in your case, if document.defaultView.getComputedStyle(elem, " ") does not return a meaningful ("truthy") value, that value is returned. Otherwise, it returns s.getPropertyValue(name).

like image 25
Spiny Norman Avatar answered Sep 21 '22 10:09

Spiny Norman