Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do people say that javascript eval() is evil but you get no objections against setTimeout and setInterval etc?

if I am not mistaken eval executes valid code in a given string

eval("alert('hey')");

and

setTimeout("alert('hey')",1000);

does just about the same thing, only with a timer. is set timeout just as risky as eval?

like image 374
Abdullah Khan Avatar asked Aug 16 '10 09:08

Abdullah Khan


People also ask

Why is it bad to use eval in JavaScript?

Malicious code : invoking eval can crash a computer. For example: if you use eval server-side and a mischievous user decides to use an infinite loop as their username. Terribly slow : the JavaScript language is designed to use the full gamut of JavaScript types (numbers, functions, objects, etc)… Not just strings!

What is wrong with eval ()?

eval() function is rarely used in the modern JavaScript because of its high vulnerability and performance reasons. Misusing the function can lead to running malicious code on the user's machine and data loss.

Is eval unsafe?

eval() is a dangerous function, which executes the code it's passed with the privileges of the caller. If you run eval() with a string that could be affected by a malicious party, you may end up running malicious code on the user's machine with the permissions of your webpage / extension.

Why is setTimeout unsafe?

undefined is not a string, but neither is it a function, so when the timer expires, setTimeout will cast it to a string ( "undefined" ) and try to eval it. That's why you get the warning.


2 Answers

I'd say you hear the same objections. setTimeout (with string and not function parameters) is pretty much the same as eval.

If possible,

 setTimeout(function(){ alert ("hey") ; }, 1000);
like image 60
Thilo Avatar answered Sep 18 '22 06:09

Thilo


Because when people say "eval", they mean "eval and any function that is more or less equivalent to eval", but the former is much shorter to say. So the answer to your question is yes, it is as risky.

like image 43
erikkallen Avatar answered Sep 17 '22 06:09

erikkallen