Search code examples
javascriptclasseval

why do i get value not defined when using an eval() statment


var count = 0
class node{
            data;
            leftchild;
            rightchild;
            constructor(data){
                this.data = data;
            }
            addleftchild(value){
                this.leftchild = value
            }
            addrightchild(value){
                this.rightchild = value
            }
            ///getter
            get data(){
                return this.data;
            }

this is the class im using

function addnode(num){
            eval("let value = nod"+num+".data")
            console.log(value) 

when i call this function all i get as an output is tree.html:42 Uncaught ReferenceError: value is not defined at addnode the problem seems to be when i try to log value it is undefined


Solution

  • Eval code is executed as if it were in a block (reference), so this

    eval("let value = nod"+num+".data")
    console.log(value) 
    

    is roughly the same as

    {
       let value = nod5.data
    }
    console.log(value) // error because 'value' didn't survive the block
    

    You can work around this by assigning to an already existing variable:

    let value
    eval("value = nod" + num + ".data")
    

    or by moving the assignment outside eval

    let value = eval("nod" + num + ".data")
    

    The question remains open, of course, whether you need eval here in the first place. I guess you rather need an array here, so that instead of a dynamic variable nod5 you could simply use nodes[5].