Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

Possible Duplicate:
How would you overload the [] operator in javascript

Is it possible to overload the [] operator for arrays in Javascript?

For instance I would like to modify the behavior of the bracket so that when it accesses an index out of range it returns 0 instead of undedined.

I know I could probably get away with something like this:

function get(array, i) {
    return array[i] || 0;
}

But that's not really modifying the behavior of arrays the way I want.

share|improve this question
Thank you. I couldn't find the duplicate because SO's search system does not play nice with [] characters. – rahmu Sep 23 '12 at 10:14

marked as duplicate by ComFreek, Frédéric Hamidi, Juicy Scripter, Registered User, Bergi Sep 23 '12 at 10:13

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

2 Answers

[] is not an operator, and you can't override it.

You can override accessors for other javascript objects (that is override ['somespecificvalue'] for writing or reading) but not the [] of arrays.

I'll add I'm glad you can't override it. I don't see the point except in making a whole application unreadable (an application where the basic syntactic elements can't be understood before you've read the whole code to be sure there isn't a change is unreadable).

share|improve this answer

Since [] is not an operator, you can't "override" it, but you can add property to Array's prototype, which may be helpful in your specific case:

Array.prototype.get = function(i, fallback) { return this[i] || fallback; }

a = [1, 2, 3]

a.get(0, 42)
1

a.get(4, 42)
42
share|improve this answer

Not the answer you're looking for? Browse other questions tagged or ask your own question.