Wondering if this is possible and if so , how ?
var variable = true;
if (variable) {
var newVariable = "$('table').find('tr').length > 1)";
} else {
var newVariable = "$('table').find('tr').length > 4)";
}
if (newVariable){ // if $('table').find('tr').length > 1)
console.log(newVariable)
}
I would like the if to look like this by inserting using the newVariable when variable is true
if ($('table').find('tr').length > 1)){
console.log(newVariable)
}
of if variable is false then this
if ($('table').find('tr').length > 4)){
console.log(newVariable)
}
CodePudding user response:
newVariable
is a string. Using it in an if
condition is not going to execute it, it will just test if the string is empty or not.
You can use a function instead, and call it in the if
.
var variable = true;
if (variable) {
var newVariable = () => $('table').find('tr').length > 1;
} else {
var newVariable = () => $('table').find('tr').length > 4;
}
if (newVariable()){
console.log(newVariable)
}
CodePudding user response:
Unclear why you would need to use strings. Only way you could do that is use eval or new Function and that is not a good idea. Seems like the code could be cleaned up to be either
var newVariable;
if (variable) {
newVariable = $('table').find('tr').length > 1;
} else {
newVariable = $('table').find('tr').length > 4;
}
if (newVariable) {
console.log('here');
}
better yet reducing the code with ternary
const minNumElems = variable ? 1 : 4;
const isValid = $('table').find('tr').length > minNumElems;
if (isValid) {
console.log('here');
}
Or better yet using ternary