Search code examples
javascripteval

How to use dynamic string in eval


let value = 'italic';
let varname = "fontSizeTitle";
eval(varname + "=" + value);

console.log(fontSizeTitle)

I have a big project in which i use eval() to assign dynamic variables to dynamic strings. The problem here is it throws an error saying italic is not defined but when if i want to use value as a string but again being dynamic? how do i tell eval() that i want the value to be dynamic. Sorry for not posting my project code but its the exact scenario in here too.


Solution

  • Is italic a string literal as opposed to a variable name? If so, you must surround it with quotes in order to set it.

    Your current eval statement does this:

    fontSizeTitle = italic
    

    This is possibly what it should be:

    fontSizeTitle = 'italic'
    

    The following code snippet will show this working:

    let value = 'italic';
    let varname = "fontSizeTitle";
    let statement = varname + "='" + value + "'";
    console.log(statement);
    eval(statement );
    
    console.log(fontSizeTitle)

    I've added the statement itself to the console log so you can see what is actually being executed.