Javascript eval()

Introduction

The Javascript eval() function evaluates JavaScript code in a string.

eval(string)
Parameters Meaning
string A string representing JavaScript code.
let a = eval(new String('2 + 2'));
console.log(a);//w  ww .  j a v a2s .  c  o m
a = eval('2 + 2');
console.log(a);

var expression = new String('2 + 2');
a = eval(expression.toString());
console.log(a);

The eval() method works like a Javascript interpreter.

It 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"); 

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

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

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

eval("function sayHi() { console.log('hi'); }"); 
sayHi(); 

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



PreviousNext

Related