To add the size() method to the Array object I do:
if (!Array.size) {
    Array.prototype.size = function() {
        return this.length;
    };
}
Is there a simple way to define the size property that will work like length ?
(I don't really need it, I just want to understand if this is something easily achievable in Javascript.)
With ES5 it's possible. Add a size property on the Array prototype,
Object.defineProperty(Array.prototype, "size", {
    get: function() {
        return this.length;
    },
    set: function(newLength) {
        this.length = newLength;
    }
});
var x = [1, 2, 3];
x.length    // 3
x.size      // 3
x.push(4);
x           // [1, 2, 3, 4]
x.length    // 4
x.size      // 4
x.length = 2;
x           // [1, 2]
x.size = 1;
x           // [1]
It basically works as a wrapper around length. Appears like a property to the naked eye, but is backed by an underlying function.
Thanks to @Matthew's comment, this size property works like a complete wrapper around length.
I'll assume you already know this is not a real life issue.
length property is modified to suit the size of the array and reflected by methods such as shift() and pop().
So, you would need a method to get the length property.
Anurag shows you how it can be done with ES5.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With