Is there any way to have JavaScript variables in an eval() statement?

twitter logo github logo ・1 min read

Hey, so I am trying to use a while_else() statement in JavaScript.

//Overview of the parameters
function while_else(/*String*/ conditions, /*function*/ body, /*function*/ exit) {
if(eval(conditions)) {


if(!eval(conditions)) {

return 1


return 0


but I want to use a variable in the eval, like this example:

var x = 0
while_else("x < 10",function {
},function() {
console.log("out of loop")

is there anyway to do this?

//I tried both
//But it only takes the value once...

So is there anyway to do this in JavaScript?

twitter logo DISCUSS (4)
markdown guide

Please don't ever use eval(). It can be dangerous if you don't know what you're doing. If you need a custom condition to be used in a loop, put that logic in a new function and pass that function as a parameter to while_else


This ^

DO NOT use eval, even if you do know what you're doing. There is very few situations where there isn't a better alternative.

See never use eval! from MDN.


Well, instead of evaling a string, you could send in a predicate function to evaluate the condition:

const while_else = (predicate, body, exit) => {
    if (predicate()) {
        while_else(predicate, body, exit)
    } else { // Do you really need to check for `!condition` after checking for `condition`?

let x = 0

const isLowerThanTen = () => x < 10

const logAndIncX = () => {
    x += 1

const outOfLoop = () => {
    console.log('Out of loop')


Although, to be fair, this is a mess and hard to follow. Are you sure that a while/else is the best approach to whatever problem you are trying to solve? Maybe you can share the actual problem you want to solve and we can give you a more idiomatic approach in Javascript.

function createFunction(text) {
   return Function(`return function a(x) { "use strict"; return ${text}};`)();

const fx = createFunction("x > 10 ? 10 : x");



Best way is to use Function instead of eval, though it is still subjected to many risks, it should be used with great care.

If there are other alternatives, please use all other alternatives apart from this.

Classic DEV Post from May 4

The secret that the fonts industry doesn't want you to know

Finally the story of CSS's most unsung hero

PDS OWNER CALIN (Calin Baenen) profile image
I am a 13 (as of Oct 30 of 2019) yr/o developer who makes projects in languages like: Java, HTML, Python, JS, CSS, C, and am working on learning C++, and C#.