To eval or not to eval?


eval("") in Javascript can be useful, but it can also be harmful. When should you use eval? And should you use new Function([], "") instead?

When and why you shouldn’t use eval

First off, you obviously shouldn’t use eval for things like eval("alert('Hi!')"). You also shouldn’t use eval when you’re getting code from the user, and you don’t want them to have access to local variables. That’s what new Function is for. And secondly, if you execute the following code, you can see that eval is up to 33x slower, if not more.

function executionTime(code) {
	var t0 = performance.now()
	code()
	var t1 = performance.now()
	return t1 - t0
}

console.log(executionTime(function() {
	var x = "Hi!"
}))

console.log(executionTime(function() {
	eval('var x = "Hi!"')
}))


In some cases, var x = "Hi!" even takes 0 seconds! (Of course, it actually doesn’t, but you can see how little time it takes compared to eval)

When you should use eval

There are a few cases where you do want to use eval, but sometimes new Function([], "") is better. It just depends. You might use eval when you need to run Javascript dynamically, but most of the time, new Function([], "") is better for that.

Leave a Reply

Your email address will not be published. Required fields are marked *