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)) {

body()
while_else(conditions,body,exit)

}
if(!eval(conditions)) {

exit()
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 {
console.log(x)
x++
},function() {
console.log("out of loop")
})

is there anyway to do this?

//I tried both
"x"
//And
`${x}`
//But it only takes the value once...

So is there anyway to do this in JavaScript?
Thanks!
Cheers!

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()) {
        body()
        while_else(predicate, body, exit)
    } else { // Do you really need to check for `!condition` after checking for `condition`?
        exit()
    }
}

let x = 0

const isLowerThanTen = () => x < 10

const logAndIncX = () => {
    console.log(x)
    x += 1
}

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

while_else(
    isLowerThanTen,
    logAndIncX,
    outOfLoop
)

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");

console.log(fx(2));

console.log(fx(12));

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 Feb 25

The Best Way to Advance Your Career

Where I answer a query from one of my awesome readers about how to advance your career based on my experience.

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#.