I just solved this challenge on freecodecamp
Remove all falsy values from an array. Return a new array; do not mutate the original array.
Falsy values in JavaScript are false, null, 0, "", undefined, and NaN.
Hint: Try converting each value to a Boolean.
i solved mine this way:
function bouncer(arr) {
return arr.filter(function(ele){return ele});
}
as opposed to this solved by freecodecamp:
function bouncer(arr) {
var check = arr.filter(function(i) {
return Boolean(i);
});
return check;
}
I can't understand why mine works correctly when called with bouncer([7, "ate", "", false, 9]);, since i'm just returning the variable in the test function without doing the boolean conversion.
JavaScript has the concept of Truthy and Falsy values.
Using Array.filter(Boolean) or Array.filter(ele => ele) is pretty much the same. Boolean will cast your value to a boolean value which can only be true or false. If you return just the value, it gets evaluated either as truthy or falsy.
If you would like to write it in a very explicit way you could do the following:
Array.filter(ele => {
return ele !=== undefined || ele !== null || ele !== false || ele !== '' || ele !== 0 || ele !== NaN
})
I am looking for check, if my variable is one of : null || undefined || empty string || false
Right now its look messy and long:
const userHasPhoneNumber = user.phone === undefined ||
user.phone === "" ||
user.phone === false ||
user.phone === null ? false : true;
Is there shortcut?
You can shortcut x === undefined || x === null to x == null. For the others, there is no shortcut as there are some falsy number values as well. You could however do
const userHasPhoneNumber = typeof user.phone == "number" || !!user.phone
If you coerce that string to a boolean then it should check all your conditions, which is pretty much checking if user.phone is truthy.
It depends how you want to use it. If you wanted to use it in a condition, i.e. if(userHasPhoneNumber) ... then you can use the string directly : if(user.phone) as it will coerce to a boolean.
If you really need to have a boolean variable then need to cast it to a boolean explicitely:
Either through
const userHasPhoneNumber = Boolean(user.phone);
or
const userHasPhoneNumber = !!user.phone;
Note, as #Bergi commented, that there are more values that are coerced to a false value (falsy values), for example NaN or the number 0 (the string "0" will coerce to true), so it depends what your input is. If it's never a number but either a string/boolean/null/undefined, it should be fine. Here is the list of all falsy values for reference : https://developer.mozilla.org/en-US/docs/Glossary/Falsy
Use JavaScript's !!, witch will become false for null, "", undefined and false:
const user = {
phone_1: null,
phone_2: "",
phone_3: undefined,
phone_4: false
};
console.log(!!user.phone_1); // false
console.log(!!user.phone_2); // false
console.log(!!user.phone_3); // false
console.log(!!user.phone_4); // false
Note Use this with caution as some results may be different then expected, this answer shows a complete list.
I want to add some defensive coding to the following check. I have 3 strings and I want to know if any of them have anything in them (for my purposes, null or undefined means they do not have anything in them).
if (twitterUrl.length + facebookUrl.length + linkedInUrl.length > 0) {
This works, but feels like very bulky. I use TypeScript and not sure if there is anything there that can help me with this.
if ((twitterUrl ? twitterUrl.length : 0) +
(facebookUrl ? facebookUrl.length : 0) +
(linkedInUrl ? linkedInUrl.length : 0) > 0) {
You can use the fact that empty strings are falsy¹. If you know they'll be strings or null or undefined and you don't need to worry about strings with just whitespace in them (" " is truthy¹), then:
if (twitterUrl || facebookUrl || linkedInUrl) {
If you need to worry about trimming, then a helper function is probably in order:
function present(s) {
return s && (typeof s !== "string" || s.trim());
}
and
if (present(twitterUrl) || present(facebookUrl) || present(linkedInUrl)) {
or
if ([twitterUrl, facebookUrl, linkedInUrl].some(present)) {
¹ falsy and truthy: When you use a value in a condition (like an if), JavaScript will implicitly coerce the value to a boolean. A value that coerces to false is falsy; one that coerces to true is truthy. The falsy values are "", null, undefined, 0, NaN, and of course, false. All other values (including " ") are truthy.
You could define a function as the following one:
function getLength(s){
if(typeof s !== "string") return 0;
return s.length;
}
and then use it like below:
if (getLength(twitterUrl) > 0 || getLenght(facebookUrr) > 0 || getLength(linkedInUrl){
// code
}
Essentially, getLength check if the value you pass when you call the function is a string and if so it returns its length. Otherwise, it returns 0. So in order to achieve that you want, (I want to know if any of them have anything in them), you have to check one by one the strings you have, if the first string has a length greater than zero, there isn't any need to continue the check for the other two strings. Otherwise you call the function on the second string and so on and so forth.
Try like this, normal if statement also works
const socialLinks = [twitterUrl, facebookUrl, linkedInUrl];
const hasSomething = socialLinks.some(social => social);
Here is falsy value like null, undefined, '' and etc., https://developer.mozilla.org/en-US/docs/Glossary/Falsy
if social are empty string('') or null or undefined then it's return false. We omitted return keyword because arrow function has implicit return behaviour.
This is a solution using some(), which checks whether at least one element in the array passes the test implemented by the provided function.
var twitterUrl, facebookUrl, linkedInUrl;
linkedInUrl = 'nonEmpty';
result = [twitterUrl, facebookUrl, linkedInUrl].some(arrVal => arrVal);
console.log(result);
Is there any check if a value is not null and not empty string in Javascript? I'm using the following one:
var data; //get its value from db
if(data != null && data != '') {
// do something
}
But I'm wondering if there is another better solution. Thanks.
If you truly want to confirm that a variable is not null and not an empty string specifically, you would write:
if(data !== null && data !== '') {
// do something
}
Notice that I changed your code to check for type equality (!==|===).
If, however you just want to make sure, that a code will run only for "reasonable" values, then you can, as others have stated already, write:
if (data) {
// do something
}
Since, in javascript, both null values, and empty strings, equals to false (i.e. null == false).
The difference between those 2 parts of code is that, for the first one, every value that is not specifically null or an empty string, will enter the if. But, on the second one, every true-ish value will enter the if: false, 0, null, undefined and empty strings, would not.
Instead of using
if(data !== null && data !== '' && data!==undefined) {
// do something
}
You can use below simple code
if(Boolean(value)){
// do something
}
Values that are intuitively “empty”, like 0, an empty string, null, undefined, and NaN, become false
Other values become true
Both null and an empty string are falsy values in JS. Therefore,
if (data) { ... }
is completely sufficient.
A note on the side though: I would avoid having a variable in my code that could manifest in different types. If the data will eventually be a string, then I would initially define my variable with an empty string, so you can do this:
if (data !== '') { ... }
without the null (or any weird stuff like data = "0") getting in the way.
if (data?.trim().length > 0) {
//use data
}
the ?. optional chaining operator will short-circuit and return undefined if data is nullish (null or undefined) which will evaluate to false in the if expression.
I often test for truthy value and also for empty spaces in the string:
if(!(!data || data.trim().length === 0)) {
// do something here
}
If you have a string consisting of one or more empty spaces it will evaluate to true.
Simple solution to check if string is undefined or null or "":-
const value = null;
if(!value) {
console.log('value is either null, undefined or empty string');
}
Both null and empty could be validated as follows:
<script>
function getName(){
var myname = document.getElementById("Name").value;
if(myname != '' && myname != null){
alert("My name is "+myname);
}else{
alert("Please Enter Your Name");
}
}
try it----------
function myFun(){
var inputVal=document.getElementById("inputId").value;
if(inputVal){
document.getElementById("result").innerHTML="<span style='color:green'>The value is "+inputVal+'</span>';
}
else{
document.getElementById("result").innerHTML="<span style='color:red'>Something error happen! the input May be empty.</span>";
}
}
<input type="text" id="inputId">
<input type="button" onclick="myFun()" value="View Result">
<h1 id="result"></h1>
I got so fed up with checking for null and empty strings specifically, that I now usually just write and call a small function to do it for me.
/**
* Test if the given value equals null or the empty string.
*
* #param {string} value
**/
const isEmpty = (value) => value === null || value === '';
// Test:
isEmpty(''); // true
isEmpty(null); // true
isEmpty(1); // false
isEmpty(0); // false
isEmpty(undefined); // false
When we code empty in essence could mean any one of the following given the circumstances;
0 as in number value
0.0 as in float value
'0' as in string value
'0.0' as in string value
null as in Null value, as per chance it could also capture undefined or it may not
undefined as in undefined value
false as in false truthy value, as per chance 0 also as truthy but what if we want to capture false as it is
'' empty sting value with no white space or tab
' ' string with white space or tab only
In real life situation as OP stated we may wish to test them all or at times we may only wish to test for limited set of conditions.
Generally if(!a){return true;} serves its purpose most of the time however it will not cover wider set of conditions.
Another hack that has made its round is return (!value || value == undefined || value == "" || value.length == 0);
But what if we need control on whole process?
There is no simple whiplash solution in native core JavaScript it has to be adopted. Considering we drop support for legacy IE11 (to be honest even windows has so should we) below solution born out of frustration works in all modern browsers;
function empty (a,b=[])
{if(!Array.isArray(b)) return;
var conditions=[null,'0','0.0',false,undefined,''].filter(x => !b.includes(x));
if(conditions.includes(a)|| (typeof a === 'string' && conditions.includes(a.toString().trim())))
{return true;};
return false;};`
Logic behind the solution is function has two parameters a and b, a is value we need to check, b is a array with set conditions we need to exclude from predefined conditions as listed above. Default value of b is set to an empty array [].
First run of function is to check if b is an array or not, if not then early exit the function.
next step is to compute array difference from [null,'0','0.0',false,undefined,''] and from array b. if b is an empty array predefined conditions will stand else it will remove matching values.
conditions = [predefined set] - [to be excluded set]
filter function does exactly that make use of it.
Now that we have conditions in array set all we need to do is check if value is in conditions array.
includes function does exactly that no need to write nasty loops of your own let JS engine do the heavy lifting.
Gotcha
if we are to convert a into string for comparison then 0 and 0.0 would run fine however Null and Undefined would through error blocking whole script. We need edge case solution. Below simple || covers the edge case if first condition is not satisfied. Running another early check through include makes early exit if not met.
if(conditions.includes(a)|| (['string', 'number'].includes(typeof a) && conditions.includes(a.toString().trim())))
trim() function will cover for wider white spaces and tabs only value and will only come into play in edge case scenario.
Play ground
function empty (a,b=[]){
if(!Array.isArray(b)) return;
conditions=[null,'0','0.0',false,undefined,''].filter(x => !b.includes(x));
if(conditions.includes(a)||
(['string', 'number'].includes(typeof a) && conditions.includes(a.toString().trim()))){
return true;
}
return false;
}
console.log('1 '+empty());
console.log('2 '+empty(''));
console.log('3 '+empty(' '));
console.log('4 '+empty(0));
console.log('5 '+empty('0'));
console.log('6 '+empty(0.0));
console.log('7 '+empty('0.0'));
console.log('8 '+empty(false));
console.log('9 '+empty(null));
console.log('10 '+empty(null,[null]));
console.log('11 dont check 0 as number '+empty(0,['0']));
console.log('12 dont check 0 as string '+empty('0',['0']));
console.log('13 as number for false as value'+empty(false,[false]));
Lets make it complex - what if our value to compare is array its self and can be as deeply nested it can be. what if we are to check if any value in array is empty, it can be an edge business case.
function empty (a,b=[]){
if(!Array.isArray(b)) return;
conditions=[null,'0','0.0',false,undefined,''].filter(x => !b.includes(x));
if(Array.isArray(a) && a.length > 0){
for (i = 0; i < a.length; i++) { if (empty(a[i],b))return true;}
}
if(conditions.includes(a)||
(['string', 'number'].includes(typeof a) && conditions.includes(a.toString().trim()))){
return true;
}
return false;
}
console.log('checking for all values '+empty([1,[0]]));
console.log('excluding for 0 from condition '+empty([1,[0]], ['0']));
it simple and wider use case function that I have adopted in my framework;
Gives control over as to what exactly is the definition of empty in a given situation
Gives control over to redefine conditions of empty
Can compare for almost for every thing from string, number, float, truthy, null, undefined and deep arrays
Solution is drawn keeping in mind the resuability and flexibility. All other answers are suited in case if simple one or two cases are to be dealt with. However, there is always a case when definition of empty changes while coding above snippets make work flawlessly in that case.
function validateAttrs(arg1, arg2, arg3,arg4){
var args = Object.values(arguments);
return (args.filter(x=> x===null || !x)).length<=0
}
console.log(validateAttrs('1',2, 3, 4));
console.log(validateAttrs('1',2, 3, null));
console.log(validateAttrs('1',undefined, 3, 4));
console.log(validateAttrs('1',2, '', 4));
console.log(validateAttrs('1',2, 3, null));
I want to guard my functions against null-ish values and only continue if there is "defined" value.
After looking around the solutions suggested to double equal to undefined: if (something == undefined). The problem with this solution is that you can declare an undefined variable.
So my current solution is to check for null if(something == null) which implicetly checks for undefined. And if I want to catch addionalty falsy values I check if(something).
See tests here: http://jsfiddle.net/AV47T/2/
Now am I missing something here?
Matthias
The standard JS guard is:
if (!x) {
// throw error
}
!x will catch any undefined, null, false, 0, or empty string.
If you want to check if a value is valid, then you can do this:
if (Boolean(x)) {
// great success
}
In this piece, the block is executed if x is anything but undefined, null, false, 0, or empty string.
The only safe way that I know of to guard against really undefined variables (meaning having variable name that were never defined anywhere) is check the typeof:
if (typeof _someUndefinedVarName == "undefined") {
alert("undefined");
return;
}
Anything else (including if (!_someUndefinedVarName)) will fail.
Basic example: http://jsfiddle.net/yahavbr/Cg23P/
Remove the first block and you'll get:
_someUndefinedVarName is not defined
Only recently discovered using '&&' as a guard operator in JS. No more If statements!
var data = {
person: {
age: 22,
name: null
}
};
var name = data.person.name && doSomethingWithName(data.person.name);
Ternary to the rescue !
(i) =>
i == 0 ? 1 :
i == 1 ? 2 :
i == 2 ? 3 :
null