0

Below code returns true. If that is the case why does 4th line in the code error out?

var x = ['a', 'e', 'f'];
x[2];
alert('2' in x);
alert(x.2);
1
  • 2
    I bet it's the same reason why you can't have something like var 2nd = "second". Identifiers can't start with a number. Commented Dec 2, 2014 at 5:32

1 Answer 1

2

The only property names you can access with the dot syntax are those that conform to JavaScript's rules for identifier names (first character is a letter, _, or $, and remaining characters are letters, numbers, _, or $).

What you have there is a syntax error, and that's why it errors out.

From MDN:

Dot notation

get = object.property;
object.property = set;

property must be a valid JavaScript identifier, i.e. a sequence of alphanumerical characters, also including the underscore ("_") and dollar sign ("$"), that cannot start with a number. For example, object.$1 is valid, while object.1 is not.

You can use the square bracket notation to access a property with any name, so either of the following will return the item you want:

x[2];
x["2"];
Sign up to request clarification or add additional context in comments.

2 Comments

function foo(a, b) { arguments[1] = 2; alert(arguments.length); } foo(1); why does it alert 1 and not 2. Its diff question!!!
@Joysamvedh If you have a different question, you should ask it as a different question, but the answer is that arguments is not an array, so it doesn't have all the behavior of an array.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.