Safe evaluation
Learn the risks of eval and the Function constructor and safer alternatives.
The risk of eval and new Function
eval and new Function run the string they receive as JavaScript code. If you pass user data through them, an attacker can run any code.
So these constructs are almost never used in applications. The same risk arises when you pass a string to setTimeout; always pass a function instead.
Bracket notation is safe
Sometimes you know a property name only at runtime. The wrong way is to use eval('obj.' + key). The right way is bracket notation: obj[key].
Bracket notation only reads a property; it runs no code. Even if the key comes from the user, it is just data access; injection is not possible. Always prefer this path for dynamic access.
Exercise Safe value access
Write a function safeGetValue, parameters obj and key. Return the property value with return obj[key].
Show example solution
First define the function, then write return obj[key].
Example solution:
function safeGetValue(obj, key) {
return obj[key];
}
Test yourself
-
Which is safe for dynamic property access?
const obj = { a: 1, b: 2 }; const key = getUserInput(); // access a property of obj- eval('obj.' + key)
- new Function('return obj.' + key)()
- setTimeout('obj.' + key, 0)
- obj[key]
Show answer
obj[key] — Correct! obj[key] only reads a property; it runs no code.
-
Complete the bracket access
const value = config[____];Show answer
const value = config[key]; -
Match the access methods
- eval
- runs code
- new Function
- creates code
- obj[key]
- reads a property
- setTimeout(fn)
- schedules