Skip to content

Instantly share code, notes, and snippets.

@bradoyler
Last active March 3, 2016 14:13
Show Gist options
  • Save bradoyler/bda5ae43556b9345a640 to your computer and use it in GitHub Desktop.
Save bradoyler/bda5ae43556b9345a640 to your computer and use it in GitHub Desktop.
Handy Util (Node.js) for when you expect an Array....and want to avoid "Object.forEach is not a function" errors.
var forceArray = function(val) {
if ( Array.isArray( val ) ) return val;
if ( !val ) return [];
return [ val ];
}
// usage:
var test1 = {id:1};
forceArray(test1) // returns [{id:1}]
var test2 = "test";
forceArray(test2) // returns ["test"]
var test3;
forceArray(test3) // returns []
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment