Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading