0

While reverse-engineering some obfuscated JavaScript code for a CTF, I came across the following syntax:

array['push']('5');

It pushes '5' at the end of the array, which seems logical, but I just do not understand why this syntax works, since I haven't managed to find anything about it (not on the Mozilla Developer Network, not on the W3C website, and the latest ECMAScript specification is a bit too dense for me to understand).

I'm thinking it has something to do with arrays being a special case of objects, but I'm not versed enough in JavaScript to figure it out.

1
  • 6
    array['push'] means exactly the same thing as array.push. It has nothing to do with arrays being special. That's the normal and universal way that object property access works in JavaScript. Commented Oct 9, 2019 at 22:25

2 Answers 2

3

In JavaScript, you can access object properties either using dot notation or square brackets. So object.propertyname is equivalent to object['propertyname']. Normally we use square brackets when the property name is calculated dynamically or is not a valid identifier (e.g. it contains special characters). But there's nothing prohibiting using it in other contexts. So array['push'] is equivalent to array.push, and therefore array['push'](5) is equivalent to array.push(5).

Sign up to request clarification or add additional context in comments.

Comments

0

array['push']('5'); translates to:

const array = [];
array.push('5');

Since push is always a method on arrays, it can be accessed via association like ['push'] or directly as a property.

3 Comments

The OP did not show where array was declared (as const). So, the translation isn't necessarily exact.
5 is not '5'
@UdoE. Its not supposed to be an exact translation. Its simply demonstrating the core concepts via code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.