0

I want to add a property to the object Array. I've been trying the following:

Array.prototype.isEmpty = array => (array || []).length <= 0 // only works if I use array.isEmpty(array) which isn't exactly what I want.

Array.prototype.isEmpty = (() => (this || []).length <= 0)() // always returns true since this is always undefined.

Is there a way to add this in JavaScript?

Henny Lee
  • 2,682
  • 3
  • 16
  • 31
  • 1
    Have you tried `Array.prototype.isEmpty = function() { return (this ....` ? – Foxhoundn Jan 13 '19 at 14:24
  • Don't us arrow function syntax for methods. Btw, have a look at [How to define method in javascript on `Array.prototype` so that it doesn't appear in for in loop](https://stackoverflow.com/q/13296340/1048572) – Bergi Jan 13 '19 at 14:24
  • Read [Why is extending native objects a bad practice?](https://stackoverflow.com/questions/14034180/why-is-extending-native-objects-a-bad-practice) – str Jan 13 '19 at 14:25
  • `Array.prototype.isEmpty = function() { return !!this.length }`. – connexo Jan 13 '19 at 14:34
  • [When to/not use arrow functions](https://www.startpage.com/do/dsearch?query=don%27t+use+arrow+functions+for+everything&cat=web&pl=ext-ff&language=english). – Andy Jan 13 '19 at 14:36

0 Answers0