1

So, code below throws undefined if index is not existing in the array

Note: it's array of arrays

arr[index] = arr[index].concat(data);

Eventually I've fixed it with check

if (!array[index]) {
   array[index]=[];
}

Which solved the problem.

Question: is there any JavaScript trick which could solve this problem easier (less lines of code, without checks, whatever)?

1
  • Both of the proposed answers still involve a check like your original if statement, they just present it in a different way. Commented Sep 22, 2015 at 17:12

3 Answers 3

1

You can use the || oprator:

arr[index] = (arr[index] || []).concat(data);

It will check if the arr[index] is a truthy value (not null, undefined, NaN, "" and 0).

If it is, it will use it, and if it's not, it will use the [] to concat to data.

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

Comments

1

In ES6:

((a = []) => a.concat(data))(array[index])

but this boils down to mere code golf, although it does have the advantage that it's a few characters shorter, and the [] default will be used only if array[index] is missing (undefined).

Comments

0

Not without compromising readability:

array[index] = (array[index] ? array[index] : []).concat(data);

Note that this and the method of using the || operator:

array[index] = (array[index] || []).concat(data);

Are both technically unsafe since they check if array[index] is truthy.

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.