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
How to Replace null with "-" JavaScript
In JavaScript, you often need to replace null, undefined, empty strings, and other falsy values with a default placeholder like "-". This is common when displaying data in tables or forms where empty values should show a dash instead of being blank.
Understanding Falsy Values
JavaScript considers these values as falsy: null, undefined, '' (empty string), 0, NaN, and false. We can use this to our advantage when replacing them.
Method 1: Using Object.keys() and forEach()
This approach iterates through all object keys and replaces falsy values in place:
const obj = {
key1: 'Hello',
key2: 'World',
key3: '',
key4: 45,
key5: 'can i use arrays',
key6: null,
key7: 'fast n furious',
key8: undefined,
key9: '',
key10: NaN,
};
const swapValue = (obj) => {
Object.keys(obj).forEach(key => {
if (!obj[key]) {
obj[key] = '-';
}
});
};
swapValue(obj);
console.log(obj);
{
key1: 'Hello',
key2: 'World',
key3: '-',
key4: 45,
key5: 'can i use arrays',
key6: '-',
key7: 'fast n furious',
key8: '-',
key9: '-',
key10: '-'
}
Method 2: Using for...in Loop
Alternative approach using a traditional for...in loop:
const data = {
name: 'John',
age: null,
email: '',
phone: undefined,
city: 'New York'
};
const replaceFalsyValues = (obj) => {
for (let key in obj) {
if (!obj[key]) {
obj[key] = '-';
}
}
return obj;
};
console.log(replaceFalsyValues(data));
{ name: 'John', age: '-', email: '-', phone: '-', city: 'New York' }
Method 3: Creating a New Object
If you prefer not to modify the original object, create a new one:
const original = {
title: 'Article',
content: null,
author: '',
date: '2024-01-01'
};
const replaceNullValues = (obj) => {
const newObj = {};
for (let key in obj) {
newObj[key] = obj[key] || '-';
}
return newObj;
};
console.log('Original:', original);
console.log('Modified:', replaceNullValues(original));
Original: { title: 'Article', content: null, author: '', date: '2024-01-01' }
Modified: { title: 'Article', content: '-', author: '-', date: '2024-01-01' }
Comparison
| Method | Modifies Original | Performance | Use Case |
|---|---|---|---|
| forEach() | Yes | Good | In-place modification |
| for...in | Yes | Best | Simple iteration |
| New Object | No | Good | Preserve original data |
Key Points
The !obj[key] condition catches all falsy values including null, undefined, empty strings, NaN, and 0. Be careful with the number 0 - if it's a valid value in your use case, add a specific check: if (obj[key] == null || obj[key] === '').
Conclusion
Replacing null and falsy values with "-" is straightforward using JavaScript's truthy/falsy evaluation. Choose the method based on whether you need to preserve the original object or modify it in place.
