0

How would I write in pure JavaScript an if/else statement for:

arr = (typeof arr !== "object") ? [arr] : arr;

JSLint com keeps saying: “Wrap a ternary expression in parens, with a line break after the left paren.” I have tried every possible solution but nothing works. I just want to revert to the pure JavaScript if/else because although I understand the lint warning, it stops any more warnings and it is annoying interrupts my work.

VLAZ
  • 26,331
  • 9
  • 49
  • 67
Jacey
  • 1
  • 1

3 Answers3

1

Use concat. It takes arrays or single elements and turns all into a new array.

console.log([].concat([1, 2, 3]));
console.log([].concat(1));

In your example there is no if required:

arr = [].concat(arr);

To avoid the JSLint warning (abusing Ninas example) you have to follow its guidelines:

if (!Array.isArray(array)) {
    array = [array];
}

Here is also a topic about it.

Lain
  • 3,657
  • 1
  • 20
  • 27
  • it looks handy but has a drawback, because it creates **always** a new array. – Nina Scholz Jul 21 '20 at 07:27
  • Yes, it does indeed. – Lain Jul 21 '20 at 07:28
  • This is the only solution that avoids the jslint warning and 'seems' to work ok . What does it mean if it creates a new array. What is the new array problem or disadvantage? – Jacey Jul 21 '20 at 12:53
  • It creates a new array even if the passed parameter already is one, which actually is an unnecessary action and a waste of resources. You will not feel/see a difference, yet it is not really *clean* (=lazy). – Lain Jul 21 '20 at 13:19
0

if i'm understanding you right, the answer is:

if(typeof arr !== "object")
  arr = [arr];

notice that there is no real need for the else statement.

vlad katz
  • 534
  • 3
  • 9
0

You could check directly for an array.

if (!Array.isArray(array)) array = [array];
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392