User2
User2

Reputation: 591

Store a condition as a variable. Javascript

In javaScript, is there a way to store a condition in a variable and then evaluate that condition later on.

I know this can be done using eval()

var condition = "(foo == pie);"
alert( eval(condition) );

The value of the alert above will change depending on the values of foo & pie.

Is there a similar way to do this without using eval()?

Upvotes: 9

Views: 8568

Answers (2)

jog39
jog39

Reputation: 21

Even simpler would be:

var conditionChecker = foo == pie;
alert( conditionChecker );

Upvotes: 2

Denys Séguret
Denys Séguret

Reputation: 382122

This really looks like what a function is :

var conditionChecker = function(){ return foo == pie };
alert( conditionChecker() );

Upvotes: 13

Related Questions