-2

I came across this code in JS Novice to Ninja.

const form = document.getElementsByTagname('form')[0];

const [input,button] = form.elements;

this create a const called input mapped to the value of the form[0] and another const called button mapped to form[1]

is this:

 const [input,button] = form.elements;

the same as:

const input = form.elements[0];
const button = form.elements[1];

Is that just some shorthand I've never come across? If so can someone tell me what it's called? Or am I misunderstanding what is happening here.

  • 1
    It's called *destructuring*, in this case *destructuring assignment*. The syntax on the left matches the structure of the object on the right. – Pointy Apr 22 '18 at 02:59
  • [What does this symbol mean in JavaScript?](https://stackoverflow.com/q/9549780/4642212), [Expressions and operators](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators). – Sebastian Simon Apr 22 '18 at 03:29

1 Answers1

1

const [input,button] = form.elements;

would actually be the same as

const input = form.elements[0];
const button = form.elements[1];

This is called destructuring and it can also be used for objects.

const {value} = someObject; would be the same as const value = someObject.value;

CodyKnapp
  • 109
  • 5