Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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()?

like image 672
User2 Avatar asked Jun 11 '14 07:06

User2


People also ask

How do you store conditions in a variable?

In javaScript, is there a way to store a condition in a variable and then evaluate that condition later on. var condition = "(foo == pie);" alert( eval(condition) ); The value of the alert above will change depending on the values of foo & pie .

Can I store a function in a variable JavaScript?

In JavaScript, functions are called Function Objects because they are objects. Just like objects, functions have properties and methods, they can be stored in a variable or an array, and be passed as arguments to other functions.

Can you assign an IF statement to a variable in JavaScript?

Should you define a variable inside IF statement? Honestly, there's no right or wrong answer to this question. JavaScript allows it, so you can make your decision from there.


1 Answers

This really looks like what a function is :

var conditionChecker = function(){ return foo == pie };
alert( conditionChecker() );
like image 162
Denys Séguret Avatar answered Nov 03 '22 22:11

Denys Séguret