'check and pass the variable is empty in javascript
I am trying to pass any variable is empty and alerting that this variable is empty
var foo ="ss", boo='';
var output;
if(!foo || !boo) {
output = !foo ? !boo + ' is empty';
alert(output);
}
Solution 1:[1]
Here if statement works if foo or boo is empty. So if foo is empty alert "foo" else alert "boo"
var foo ="ss", boo='';
if(!foo || !boo) {
alert(!foo ? 'foo is empty' : "boo is empty");
}
Solution 2:[2]
const foo = "ss",
boo = '';
const output = `${!foo && "foo" || !boo && "boo"} is empty`;
alert(output);
Solution 3:[3]
You are using the ternary IF operator but are missing the third (last) argument. The syntax goes CONDITION ? IF_TRUE_VALUE : ELSE_VALUE
. Check the implementation below.
var foo = "ss", boo = '';
var output;
if (!foo || !boo) {
// if foo is empty then display foo or else boo
output = (!foo ? 'foo' : 'boo') + ' is empty';
alert(output);
}
Solution 4:[4]
If you want to get the variable name, don't hardcode them into strings afterwards, such code is hard to maintain.
Use rather an Object to store your Key-Value pairs.
To later retrieve your key value pairs use Object.entries
const data = {foo:"ss", boo:"", bar:"zz", baz:""};
Object.entries(data).forEach(([k, v]) => v === "" && console.log(`${k} is empty`));
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | n-ata |
Solution 2 | Cesare Polonara |
Solution 3 | BrunoT |
Solution 4 |