Prototype pollution
Learn the prototype pollution risk and how to guard with hasOwnProperty.
The prototype pollution risk
In JavaScript, a for...in loop walks an object's own properties as well as the ones on the prototype chain. This can surface properties you did not expect.
Object.prototype.gift = 'surprise';
const obj = { name: 'Alex' };
for (const key in obj) {
console.log(key); // name, gift
}This kind of issue is close to prototype pollution. The added gift shows up where it is not wanted. Filter with hasOwnProperty to stay safe.
Safe iteration
hasOwnProperty tells you whether a property lives on the object itself or comes from the prototype chain. Inside for...in, you filter with it.
for (const key in obj) {
if (obj.hasOwnProperty(key)) {
console.log(key, obj[key]);
}
}A shorter path: Object.keys(obj) returns only own properties as an array, skipping the prototype. Both are safe; Object.keys is often more readable.
Exercise Filter inside for...in with hasOwnProperty
Define obj as { name: 'Alex', age: 28 }. Assign 'surprise' to Object.prototype.gift. Loop over obj's keys with for...in; when obj.hasOwnProperty(key) is true, call console.log(key, obj[key]). Then also print the array from Object.keys(obj).
Show example solution
Object.prototype.gift = 'surprise';
const obj = { name: 'Alex', age: 28 };
for (const key in obj) {
if (obj.hasOwnProperty(key)) {
console.log(key, obj[key]);
}
}
console.log(Object.keys(obj));
Test yourself
-
What should you do when looping with for...in?
- for...in already visits only own properties
- Filter with hasOwnProperty for own properties only
- Rebuild the object with Object.create(null)
- Delete the prototype
Show answer
Filter with hasOwnProperty for own properties only — Correct! hasOwnProperty gives you only own properties.
-
hasOwnProperty inside for...in
for (const key in obj) { if (obj.____(key)) { console.log(key); } }Show answer
for (const key in obj) { if (obj.hasOwnProperty(key)) { console.log(key); } } -
Match safe and dangerous patterns
- for...in
- includes prototype
- Object.keys
- own only
- hasOwnProperty
- own property check
- Object.prototype.x = ...
- dangerous