Safe. No throw; loops over the result simply do nothing.
Check length. Use result.length if you must know whether anything survived.
Compatibility
Browser & Runtime Support
_.compact ships with Underscore.js (1.x). It runs anywhere Underscore runs — modern browsers (CDN or bundle) and Node.js / Bun / Deno with npm install underscore.
✓ Stable · Underscore 1.x
_.compact()
Available in [email protected] (UMD / ESM). Works in evergreen browsers and current Node LTS when Underscore is loaded.
100%With Underscore 1.x
Google ChromeSupported · Desktop & Mobile
Full support
Mozilla FirefoxSupported · Desktop & Mobile
Full support
Apple SafariSupported · macOS & iOS
Full support
Microsoft EdgeSupported · Chromium
Full support
Internet ExplorerNo native support · Use a polyfill
Polyfill
OperaSupported · Modern versions
Full support
Samsung InternetSupported · Android
Full support
BunSupported · JavaScript runtime
Supported
DenoSupported · JavaScript runtime
Supported
Node.jsSupported · Server runtime
Supported
Android WebViewSupported · Modern WebView
Full support
_.compactUnderscore 1.x+
Bottom line: Safe for production once Underscore is on the page or in your bundle. Not a native browser API — load Underscore first. Prefer a pinned CDN version (e.g. [email protected]).
Frequently Asked Questions
_.compact(list) returns a copy of the list with all falsy values removed, keeping only truthy elements.
The six JavaScript falsy values: false, null, 0, "" (empty string), undefined, and NaN. Everything else is kept.
No. [] and {} are truthy in JavaScript, so they survive. So do non-empty strings like "0" and "false".
An empty array []. An array made entirely of falsy values also returns [], never an error.
_.compact is a shorthand for removing falsy values with no predicate. Use _.filter when you need a custom condition.
No. It returns a new array; the original is left unchanged.