Cleaning up arrays is a common task in JavaScript, especially when working with data from APIs, forms, or user input. Sometimes, arrays may contain unwanted values like null or undefined that can break your logic or display incorrect information. Using filter(), you can easily remove these values and ensure your array contains only meaningful data. Below is a practical example that shows how to clean an array by removing null and undefined values while keeping valid data like 0, false, or empty strings.
Why are `0`, `false`, and `””` still in the result?
Because `filter(value => value)` would remove all **falsy** values (`0`, `false`, `””`, `null`, `undefined`, `NaN`). In this example, we only want to remove `null` and `undefined`, so we check specifically for those.
How do I remove all falsy values (if I want to)?
If you want to remove **all falsy values**, you can write:
Is this safe for arrays of mixed types?
Yes, as long as you’re aware of what values you’re filtering out. Be explicit if you’re only targeting `null` or `undefined` to avoid losing valid `0` or `false` values.