Run a string of JavaScript

Description

eval() works like an interpreter and accepts a string of JavaScript to execute.

eval("console.log('hi')");

This line is functionally equivalent to the following:

console.log("hi");

When the interpreter finds an eval() call, it interprets the argument into actual ECMAScript statements and then inserts it into place.

Code executed by eval() is considered to be part of the execution context in which the call is made.

Variables defined in the containing context can be referenced inside an eval() call.


var msg = "hello world";
eval("console.log(msg)");    //"hello world"

You can define a function or variables inside an eval() call that can be referenced by the code outside.


eval("function sayHi() { console.log('hi'); }");
sayHi();
eval("var msg = 'hello world';");
console.log(msg);  //"hello world"

In strict mode, variables and functions created inside of eval() are not accessible outside.





















Home »
  Javascript »
    Javascript Reference »




Array
Canvas Context
CSSStyleDeclaration
CSSStyleSheet
Date
Document
Event
Global
History
HTMLElement
Input Element
Location
Math
Number
String
Window