PrimeLens
PrimeLens

Reputation: 2707

is it valid javascript to index with square brackets right after declaring with square brackets?

Normally I would write

arr = ['choiceA', 'choiceB', 'choiceC', 'choiceD', 'choiceE'];
position = 3;
answer = arr[position];

Just wondering... Is it valid javascript to write the following?
Will it work cross browser?

answer = ['choiceA', 'choiceB', 'choiceC', 'choiceD', 'choiceE'][position];

Upvotes: 3

Views: 136

Answers (4)

Bergi
Bergi

Reputation: 664454

Yes, array literals can be a syntactically valid left part of a member operator. It does work cross-browser.

I find this construct a very readable alternative to a lengthy switch statement, and use it with object literals as well.

Upvotes: 1

Felix Kling
Felix Kling

Reputation: 816404

Yes it is, according to the ECMAScript 5 specification:

MemberExpression :
    PrimaryExpression
    FunctionExpression
    MemberExpression [ Expression ]
    MemberExpression . IdentifierName
    new MemberExpression Arguments

where PrimaryExpression is defined as:

PrimaryExpression :
    this 
    Identifier
    Literal
    ArrayLiteral
    ObjectLiteral
    ( Expression )

So the construct ArrayLiteral[Expression] is valid.


It does not necessarily mean that it works in every browser (especially IE has something syntax quirks) but you should assume that it does.

Upvotes: 4

Marc B
Marc B

Reputation: 360662

It's valid. It's pretty much the same as doing

 some_func_that_returns_an_array()[7]

Upvotes: 1

davidbuzatto
davidbuzatto

Reputation: 9424

Yes, it will. This sintax look weird in a first look, but it is perfectly valid. You are getting a position value from an array that is not being assigned to anything.

Upvotes: 1

Related Questions