I have stumbled across a bit of code that I was hoping someone could explain to me.
This is used in the context of jqGrid.
onSelectRow: function(id){
if(id && id!==lastsel){
jQuery('#rowed3').jqGrid('restoreRow',lastsel);
jQuery('#rowed3').jqGrid('editRow',id,true);
lastsel=id;
}
},
Why use logical operators on a string in javascript as shown above? Is this simply a bug or is there some functionality here that I dont understand?
Code is taken from http://trirand.com/blog/jqgrid/rowedex3.html
Full example http://trirand.com/blog/jqgrid/jqgrid.html > Row editing > Using events
The variables should be numeri, though, the conditional would work either way.
if(id && id !== lastsel)The first
idis saying that it must have a value. The value also has to be truthy. A value istruthyif it is notfalsy, which means it just can’t be one of the following (borrowed from 11heavens.com):falsenullundefined''0NaN(NaNis of type number)Note: You will see the same kind of comparisons to
trueelsewhere in JavaScript, specifically for/while loops:The second part is saying the id can’t be equal the lastsel, which is the last id that was used.
!==is special in JavaScript meaning it must compare value and type, whereas!=just compares value:a == b: value ofaequals value ofba != b: value ofadoes not equal value ofba === b: value ofaequals value ofband type ofaequals type ofba !== b: value ofadoes not equal value ofband type ofadoes not equal type ofbEdit
Additonally, it might help to think of the expression if you saw it in parentheses:
if( (id) && (id !== lastsel) )