JavaScript - hasOwnProperty in `for-in` loops
In most programming languages, iterating over an object (dictionary or map) is natively supported. and JavaScript supports it as well.
You've might seen iterating keys over object in JavaScript looks like this:
var obj = {
a: 1,
b: 2
};
for (var k in obj) {
if (obj.hasOwnProperty(k)) {
console.log(k); // prints a, b
}
}
Actually the following code might be working as well:
var obj = {
a: 1,
b: 2
};
for (var k in obj) {
// no hasOwnProperty check
console.log(k); // prints a, b
}
Then, You might say "Why we need additional useless hasOwnProperty check?", and feel that this is useless and not natural. (Frankly, I thought so)
But this is not useless, this is very important to make your code safe and to make it always do right thing.
because JavaScript is too open to modify its inner implementations. Such as You can easily modify Object.prototype which is base prototype of all objects.
the following code is a simple example for messing up for...in loop which has no hasOwnProperty check by modifying Object.prototype:
var obj = {
a: 1,
b: 2
};
Object.prototype.haha = 3;
for (var k in obj) {
console.log(k); // prints a, b, haha
}
Someone (some libraries or some dependencies) could touch Object.prototype on your program context in anytime, Without hasOwnProperty check, your for...in loop might be iterating unexpected keys. So you need to make your for...in loop safe using hasOwnProperty check.
Object.keys()
In ES5+, You can use Object.keys() to get its own enumerable keys of an object as well. and it will be much safer and easier to understand.
the following code is one with Object.keys():
var obj = {
a: 1,
b: 2
};
Object.prototype.haha = 3;
var objKeys = Object.keys(obj);
for (var k in objKeys) {
console.log(k); // prints a, b
}
It's simple and safe.
References
Leave JavaScript - hasOwnProperty in `for-in` loops to:
Read more #programming posts
Best Posts From Heejin
We have not curated any of heejin's posts yet. But you can encourage our curation team to review posts by visiting them regularly and by referring other readers. Because we give priority to frequently read content.
More Posts From Heejin
- DELETED
- 개발자들을 위한 큐레이션 사이트를 만들어봤습니다.
- SteemConnect가 Steem용 dApp의 발전을 저해하고 있는 것 같습니다.
- Binance Chain, 바이낸스에서 자신들만의 블록체인을 만든다고 하네요
- 지금까지 스팀잇에 대한 환상을 가지고 있지 않았을까
- BTS(BitShares)가 Bittrex에서 곧 상장 폐지됩니다.
- Coinhive - 당신의 블로그로 수익을 만드는 새로운 방법 (블록체인 기반)
- JavaScript - hasOwnProperty in `for-in` loops
- JavaScript - Understanding Prototype
- JavaScript - Object.create in `Class`ical Inheritance
- Learning How to Learn
- JavaScript - var, let, const
- 정렬 알고리즘 - 거품 정렬 (Bubble sort)
- [이벤트 참여] @kimdy 님의 프로그램을 다양한 언어로
- 원어민과의 온라인 영어회화 수업 후기
- 뉴비의 스팀잇 접근을 어렵게 만드는 요소!
- If you use Facebook React, Take a look at the LICENSE carefully!
- Facebook의 React를 사용할 때 주의해야 할 라이센스 문제
- 자기계발 수단으로써의 스팀잇
- 폴로닉스에 스팀 달러를 전송했습니다, 10분 정도 지났는데 아직 안들어오네요.