Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Omitting false values while constructing string in JavaScript
We have an array that contains some string values as well as some false values like null, undefined, 0, and empty strings.
We need to write a JavaScript function that takes this array and returns a string constructed by joining values while omitting all falsy values.
Understanding Falsy Values
In JavaScript, falsy values include: false, 0, "", null, undefined, and NaN. These evaluate to false in boolean contexts.
Method 1: Using reduce() with Logical OR
The logical OR operator (||) returns the right operand when the left is falsy:
const arr = ["Here", "is", null, "an", undefined, "example", 0, "", "of", "a", null, "sentence"];
const joinArray = arr => {
const sentence = arr.reduce((acc, val) => {
return acc + (val || "");
}, "");
return sentence;
};
console.log(joinArray(arr));
Hereisanexampleofasentence
Method 2: Using filter() and join()
A cleaner approach is to filter out falsy values first, then join:
const arr = ["Here", "is", null, "an", undefined, "example", 0, "", "of", "a", null, "sentence"];
const joinArrayFiltered = arr => {
return arr.filter(Boolean).join("");
};
console.log(joinArrayFiltered(arr));
Hereisanexampleofasentence
Method 3: Adding Spaces Between Words
For more readable output, you might want spaces between valid words:
const arr = ["Here", "is", null, "an", undefined, "example", 0, "", "of", "a", null, "sentence"];
const joinWithSpaces = arr => {
return arr.filter(Boolean).join(" ");
};
console.log(joinWithSpaces(arr));
Here is an example of a sentence
Comparison
| Method | Readability | Performance | Use Case |
|---|---|---|---|
reduce() with ||
|
Medium | Good | Simple concatenation |
filter(Boolean).join() |
High | Good | Clean, readable code |
| With spaces | High | Good | Human-readable sentences |
Conclusion
Use filter(Boolean).join() for the cleanest approach to omit falsy values when constructing strings. The Boolean constructor effectively removes all falsy values from arrays.
