3

I want to extract a value from a variable. If its an array, I want the first element, and if not, I want the value of that variable. The value is a float, but I was wondering which of these are better in terms of performance, portability to non-floats, and of course short code and code readability

I want to use

value = variable[0] || variable

Its short and nice, is there any caveats is using this?

or I can do,

value = ([].concat(variable))[0]

This SO question says it's bad for performance.

And then, ofcourse, I can check if variable is an array or not in a few different ways, that is also mentioned in above question. Is there any better ways if the first one is not good?

Community
  • 1
  • 1
xcorat
  • 1,434
  • 2
  • 17
  • 34

2 Answers2

2

Your value = variable[0] || variable will work, and will work reliably. Technically, if variable is a number primitive, what the JS engine has to do at that point is promote it to an object and then look up the 0 property on that object, but as you know it won't have one, that's okay.

The only cases where that may fail are if variable is null or undefined, because neither of those can be promoted to an object, and so the expression will throw. Provided you're okay with that, then you can use that. I'd comment it, though, because it's pretty odd-looking.

If you needed to defend against null and undefined, you could use the fact that == null will filter out both of those:

value = variable == null ? undefined : variable[0] || variable;

I'd comment that, too. :-)

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
1

Having this

value = variable[0] || variable

you may go to a trouble if the first element of the array is false. For example:

var arr = [false, 1, 2, 3];
value = variable[0] || variable; // <--- value is [false, 1, 2, 3] 

So, I'll go with this:

var value = arr instanceof Array ? arr[0] : arr;

If you are not sure if the array is full then you should add one more check.

var value = arr instanceof Array && arr.length > 0 ? arr[0] : arr;
Krasimir
  • 13,306
  • 3
  • 40
  • 55