Javascript - eval() Method

Introduction

The eval() method works like an ECMAScript interpreter and accepts one argument, a string of JavaScript to execute.

Here's an example:

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

This line is functionally equivalent to the following:

console.log("hi");

When the interpreter meets an eval() call, it inserts its argument into the place.

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

The executed code has the same scope chain as that context.

The variables defined in the containing context can be referenced inside an eval() call:

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

Here, the variable msg is defined outside the eval() call, but the call to console.log() still displays the text "hello world".

The second line is replaced with a real line of code.

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

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

Any variables or functions created inside of eval() will not be hoisted. They are created only at the time of eval() execution.

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

In strict mode, assigning a value to eval causes an error:

"use strict";
eval = "hi";  //causes error