function assert(value, desc) { var res = $("#results"); var li = document.createElement("li"); li.className = value ? "pass" : "fail"; li.appendChild(document.createTextNode(desc)); res.append(li); } // eval executes the code passed to it as string // it executes in the context in which it is called // returns the value of the last executed statement assert(eval("10+20") === 30, "value returned from eval was 30"); assert(eval("var abc = 5;") === undefined, "value returned was undefined because it was just an assignment"); assert(abc === 5, "last statement was executed so abc was created"); assert(eval("cde = 6;") === 6, "however when added to global context, the assigned value is returned"); assert(window.cde === 6, "cde was added in the global scope"); assert(eval("1+1;2+2;") === 4, "returns the value of last executed statement"); //anything complex being used in eval needs to be wrapped up in parentheses //literal object var litObj = eval("({description:'this is literal object'})"); assert(litObj !== undefined && litObj.description === "this is literal object", "lit object got created with correct property"); // function object var fn = eval("(function(){return 'this is function object';})"); assert(fn !== undefined && typeof fn === "function" && fn() === "this is function object", "function object got created");
<div id="results" />
body {margin:10px;} .pass {color:green;} .fail {color:red;text-decoration:line-through;}