JavaScript eval(): How It Works, Risks, and Alternatives

eval() runs a string as JavaScript. eval('2 + 2') returns the number 4. For user input, use a parser or predefined functions that make the permitted behavior explicit.

What eval() does

The example uses a fixed string to show the return behavior. Invalid JavaScript syntax can raise SyntaxError. A non-string argument, such as a number, is returned unchanged. ECMAScript · eval()

console.log(eval('2 + 2')); // 4
console.log('2 + 2');       // '2 + 2'
console.log(eval(4));       // 4

Why running input as code is risky

If external input becomes code, it can attempt other operations available to the page beyond the intended calculation. A Content Security Policy (CSP) can block string compilation. Design new features to handle inputs as data and keep the policy in place. Content Security Policy

Choose an alternative for the task

Task Alternative
Read JSON data JSON.parse(text)
Read a property by string key object[key] (validate the allowed keys first)
Run one of several known operations function map or switch

For JSON (JavaScript Object Notation) data, use JSON.parse(). Valid syntax still leaves the fields and ranges to check. For example, if a count field is required, use Number.isInteger(data?.count) after parsing to check for an integer. ECMAScript · JSON.parse()

Build a calculator without eval

Save the code below as calculator-without-eval.html in UTF-8 and open it in a browser. The selection identifies one of four operations. Object.hasOwn() checks that the name is defined directly on the operation object before the two numbers are passed to the function. ECMAScript · Object.hasOwn()

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Calculate without eval</title>
</head>
<body>
<label for="first">First number</label>
<input id="first" type="number" step="any" value="2">
<label for="operation">Operation</label>
<select id="operation">
  <option value="add">Add</option>
  <option value="subtract">Subtract</option>
  <option value="multiply">Multiply</option>
  <option value="divide">Divide</option>
</select>
<label for="second">Second number</label>
<input id="second" type="number" step="any" value="2">
<button id="calculate" type="button">Calculate</button>
<p id="result" aria-live="polite"></p>
<script>
const operations = {
  add: (a, b) => a + b,
  subtract: (a, b) => a - b,
  multiply: (a, b) => a * b,
  divide: (a, b) => a / b
};

document.querySelector('#calculate').addEventListener('click', () => {
  const firstText = document.querySelector('#first').value.trim();
  const secondText = document.querySelector('#second').value.trim();
  const first = Number(firstText);
  const second = Number(secondText);
  const operation = document.querySelector('#operation').value;
  const result = document.querySelector('#result');

  if (!firstText || !secondText || !Number.isFinite(first) || !Number.isFinite(second)) {
    result.textContent = "Enter two finite numbers.";
    return;
  }
  if (!Object.hasOwn(operations, operation)) {
    result.textContent = "Select a supported operation.";
    return;
  }
  if (operation === 'divide' && second === 0) {
    result.textContent = "Cannot divide by zero.";
    return;
  }
  const value = operations[operation](first, second);
  if (!Number.isFinite(value)) {
    result.textContent = "The result is outside the numeric range.";
    return;
  }
  result.textContent = `Result: ${value}`;
});
</script>
</body>
</html>

Adding the default values 2 and 2 gives 4. Choose division and enter 0 as the second number to see the input message. Blank inputs, non-finite numbers, and unknown operations are rejected. If multiplying large finite numbers produces infinity, the calculator reports that the result is out of range.