Skip to content Skip to sidebar Skip to footer

Why Does Javascript Allow Array Syntax To Access Properties?

Closely related questions: associative array versus object in javascript Why does JavaScript not throw an exception for this code sample? javascript array associative AND indexed?

Solution 1:

Why does JavaScript allow array syntax to access properties?

It isn't "array syntax".

Square brackets are a standard way to access the properties of an object.

Arrays are just a type of object.

Square bracket notation has some advantages over dot notation for accessing properties:

  • You can use any expression to define the name, including variables and function calls.
  • You can access properties which have names that are invalid in an identifier (such as those which start with a number, which is why you commonly see them used to access arrays).

It's also more verbose and potentially less efficient.

the actual distinction between an associative array and a JavaScript object is, at a minimum, slightly blurry, and that that's how JavaScript is implementing object properties "under the hood"

JavaScript doesn't have a feature called "associative arrays". (W3Schools is not a trustworthy source).

It has objects, which are (at their core) collections of property:value pairs. (This is similar to PHP's associative array feature).

It has arrays, which are objects which inherit from the Array constructor, gaining methods like forEach and properties like length (which uses a getter function to determine its value based on the properties with a name that is the highest integer value).

Post a Comment for "Why Does Javascript Allow Array Syntax To Access Properties?"