Skip to content

Commit 6b0eef3

Browse files
committed
No messing with globals
1 parent 0eaa023 commit 6b0eef3

File tree

1 file changed

+57
-0
lines changed

1 file changed

+57
-0
lines changed

README.md

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -245,6 +245,63 @@ console.log(name); // 'Ryan McDermott';
245245
console.log(newName); // ['Ryan', 'McDermott'];
246246
```
247247

248+
### Don't write to global functions
249+
Polluting globals is a bad practice in JavaScript because you could clash with another
250+
library and the user of your API would be none-the-wiser until they get an
251+
exception in production. Let's think about an example: what if you wanted to
252+
extend JavaScript's native Array method to have a `diff` method that could
253+
show the difference between two arrays? You could write your new function
254+
to the `Array.prototype`, but it could clash with another library that tried
255+
to do the same thing. What if that other library was just using `diff` to find
256+
the difference between the first and last elements of an array? This is why it
257+
would be much better to just use ES6 classes and simply extend the `Array` global.
258+
259+
**Bad:**
260+
```javascript
261+
Array.prototype.diff = function(comparisonArray) {
262+
var values = [];
263+
var hash = {};
264+
265+
for (var i of comparisonArray) {
266+
hash[i] = true;
267+
}
268+
269+
for (var i of this) {
270+
if (!hash[i]) {
271+
values.push(i);
272+
}
273+
}
274+
275+
return values;
276+
}
277+
```
278+
279+
**Good:**
280+
```javascript
281+
class SuperArray extends Array {
282+
constructor(...args) {
283+
super(...args);
284+
}
285+
286+
diff(comparisonArray) {
287+
var values = [];
288+
var hash = {};
289+
290+
for (var i of comparisonArray) {
291+
hash[i] = true;
292+
}
293+
294+
for (var i of this) {
295+
if (!hash[i]) {
296+
values.push(i);
297+
}
298+
}
299+
300+
return values;
301+
}
302+
}
303+
```
304+
248305
## **Classes**
249306
### Prefer ES6 classes over ES5 plain functions
250307
It's very difficult to get readable class inheritance, construction, and method

0 commit comments

Comments
 (0)