0

I would like to ask if it's possible to write an if-statement using a string and convert it somehow into a real statement?

I wish I could use "c==c" like if(c==c). Is that possible?

var c=1;
var aa= "c==c";
if(aa) {
    console.log("abc")
}
Kristianmitk
  • 4,528
  • 5
  • 26
  • 46
Quicki
  • 391
  • 1
  • 5
  • 15
  • 1
    Perhaps a use case for [`eval()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval). However, be sure to read up on the security implications of using `eval()` (e.g., [this thread](https://stackoverflow.com/questions/86513/why-is-using-the-javascript-eval-function-a-bad-idea)). – Ted Hopp Apr 20 '18 at 15:09
  • Can you explain a bit more of your underlying problem. `eval` is widely disparaged, for some good reasons. But it or its kin (Function constructor) are the only ways to do this. Perhaps there's some better way to deal with your underlying problem. – Scott Sauyet Apr 20 '18 at 15:13
  • The structure of your string if statement will be allwasy like this "c==c"? or also other forms like this "c!=c"? – Dahou Apr 20 '18 at 15:13
  • As stated, `eval()` can do this for you, but in almost every case, when we get to the root of the real problem, we can find an alternate solution because `eval === evil`. *I wish I could use "c==c" like if(c==c)* - Why do you wish this? – Scott Marcus Apr 20 '18 at 15:16
  • It was a simple example. I want to do sth like that to enter an JSON object like `"people[i].a". But I'm not sure if it's possible to do it with `eval()` – Quicki Apr 20 '18 at 15:29

1 Answers1

1

Yes, use Javascript's eval function https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval

Eval let's you run any string as valid Javascript code. However eval has a few downsides like performance and security since this can lead to vulnerabilities in your code if you let users eval any string they want.

Aneesh Durg
  • 464
  • 4
  • 14