1

Why can’t we access this array-like object’s properties with dot notation instead of bracket notation?

function testArray(rat){
  return typeof arguments;
}

console.log(testArray("test")); // "object"

function testArray(rat){
  return arguments.0; // `arguments[0]` works.
}

console.log(testArray("test")); // Throws error.
Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75
enix
  • 113
  • 1
  • 8
  • [`arguments`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions_and_function_scope/arguments) is _"an **Array-like object** corresponding to the arguments passed to a function."_ And, no... you can't access the n-index properties via dot notation. – canon Jul 16 '13 at 14:45
  • Related: [JavaScript property access: dot notation vs. brackets?](/q/4968406/4642212) and [Can I get a javascript object property name that starts with a number?](/q/5809790/4642212). There’s also [Why javascript array element can't be accessed with dot notation?](/q/31302956/4642212) which asks about the rationale of these parsing rules. – Sebastian Simon Jan 29 '22 at 06:32

2 Answers2

6

Your question seems to be about why we can’t access array and array-like elements using the dot notation like this:

const v = a.0;

It’s described in the ECMAScript specification:

The dot notation is explained by the following syntactic conversion:

MemberExpression . IdentifierName

And identifiers may not start with a digit as described here:

IdentifierName ::
IdentifierStart
IdentifierName IdentifierPart
IdentifierStart ::
UnicodeLetter
$
_
\ UnicodeEscapeSequence

As for the reasoning, having identifier names just being made of digits would have made it difficult to write number literals. An exception could probably have been designed just for array access but that would have made the language more complex and departing from the common C family syntax without any real gain.

Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75
Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
-1

You can:

var arr = [];
arr.foo = 'foo';

console.log(arr.foo); // => 'foo'
yckart
  • 32,460
  • 9
  • 122
  • 129