4

We just made this code based on a hunch, and it worked. I'm pretty sure it's acceptable. I just want to make sure:

const state = { inProgress: true }
const actions = 'COMPLETE_RICE'
const change = { inProgress: false, rice: 'cooked' }

// Is this destructuring OK?
const {
  0: newState,
  1: newActions,
  2: newChange,
} = [state, actions, change]

console.log('New State:', newState)
console.log('New Actions:', newActions)
console.log('New Change:', newChange)

Is there a better way to do this?

Any concerns or violations?

I can't find any examples of this and only tried it because I recalled that:

['one', 'two', 'three'] can be expressed as an object:

{
  0: 'one',
  1: 'two',
  2: 'three'
}

It's not exactly listed here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment

But, it works.

2
  • It works indeed but the end result will not inherit the Array prototype functions so why not destructuring with a simple array ? const [newState, newActions, newChange] = [state, actions, change] Commented Nov 21, 2017 at 8:48
  • You can use object to extract vars like this. Result will be the same as using const [newState, newActions, newChange] = [state, actions, change] but using object like you are doing is just not too nice. It will work but why doing it weird way :) Commented Nov 21, 2017 at 8:58

2 Answers 2

6

You could use an array for a destructuring assignment. There you need no indices, because the array gives the order.

const state = { inProgress: true }
const actions = 'COMPLETE_RICE'
const change = { inProgress: false, rice: 'cooked' }

// Is this destructuring OK?
const [newState, newActions, newChange] = [state, actions, change];

console.log('New State:', newState)
console.log('New Actions:', newActions)
console.log('New Change:', newChange)

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

Comments

2

Instead of destructuring an array as an object, use array destructuring:

const state = { inProgress: true }
const actions = 'COMPLETE_RICE'
const change = { inProgress: false, rice: 'cooked' }

const [newState, newActions, newChange] = [state, actions, change]

console.log('New State:', newState)
console.log('New Actions:', newActions)
console.log('New Change:', newChange)

Comments

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.