user1032531
user1032531

Reputation: 26311

Using anonymous functions in JavaScript IF statement

How do I use an anonymous function in a if statement? Please feel free to use the following as an example. Thank you

if(function(){return false;} || false) {alert('true');}

Reference https://jsfiddle.net/san22xhp/

Upvotes: 1

Views: 923

Answers (2)

flyandi
flyandi

Reputation: 1939

Use the .call() method of the function constructor:

if(function(){return false;}.call() || false) { alert('true'); }

The advantage with this method is that you can pass variables to it, e.g.:

if(function(){return arguments[0] == 7;}.call(null, 7) === true) alert('yeah it is 7');

https://jsfiddle.net/f8175o2v/3/

Upvotes: 1

m0meni
m0meni

Reputation: 16445

Wrap the function in parenthesis and then call it immediately after like this:

if((function(){return false;})() || false) {alert('true');}

Fiddle: https://jsfiddle.net/Ar14/7p2ompod/

Upvotes: 1

Related Questions