Another use of ‘||’ and ‘&&’ operators in javascript.

1. Another use of ‘&&’ operator
Consider following javascript if statement i.e. invoke callback if there is one.

[code language=”js”]
if(callback){
callback();
}
[/code]

Same above task can achieved in js with ease as follows.

[code language=”js”]
callback && callback();
[/code]

2. Another use of ‘||’ operator
Consider following javascript if statement i.e. if evt is not javascript falsy value then assign it window.event object, here we assigning default values to evt variable if is javascript falsy value.

[code language=”js”]
if (!evt) {
evt = window.event;
}
[/code]

Same above task can achieved in js with ease as follows.

[code language=”js”]
evt = evt || window.event;
[/code]

References

https://javascriptweblog.wordpress.com/2010/07/26/no-more-ifs-alternatives-to-statement-branching-in-javascript/
http://stackoverflow.com/questions/5049006/using-s-short-circuiting-as-an-if-statement

Leave a Reply

Your email address will not be published. Required fields are marked *