When I started learning JS, one of the most powerful tools I discovered, was the ability to check if a variable is empty.
My definition of emptiness was hardly a scientific one as I didn’t mean to check if it was defined or not. I wanted to take full advantage of JavaScript as a dynamically typed language.
So, I had a function that should do something useful when it’s supplied with a valid (non-empty) argument.
const doSomethingUseful = (param) => {
if (!param) {
console.log('param is missing or empty');
return false;
}
console.log(param);
// ... the rest of the logic follows
}
In this example if you call the function doSomethingUseful
with a falsy value, it will print the string
param is missing or empty
and return false
.
Here’s how it works:
doSomethingUseful();
doSomethingUseful(false);
doSomethingUseful(0);
doSomethingUseful('');
doSomethingUseful(null);
doSomethingUseful(undefined);
In all these cases, you’ll see the string param is missing or empty
logged to the console.