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.
Related
How do I check a variable if it's null or undefined and what is the difference between the null and undefined?
What is the difference between == and === (it's hard to search Google for "===" )?
How do I check a variable if it's null or undefined...
Is the variable null:
if (a === null)
// or
if (a == null) // but see note below
...but note the latter will also be true if a is undefined.
Is it undefined:
if (typeof a === "undefined")
// or
if (a === undefined)
// or
if (a == undefined) // but see note below
...but again, note that the last one is vague; it will also be true if a is null.
Now, despite the above, the usual way to check for those is to use the fact that they're falsey:
if (!a) {
// `a` is falsey, which includes `undefined` and `null`
// (and `""`, and `0`, and `NaN`, and [of course] `false`)
}
This is defined by ToBoolean in the spec.
...and what is the difference between the null and undefined?
They're both values usually used to indicate the absence of something. undefined is the more generic one, used as the default value of variables until they're assigned some other value, as the value of function arguments that weren't provided when the function was called, and as the value you get when you ask an object for a property it doesn't have. But it can also be explicitly used in all of those situations. (There's a difference between an object not having a property, and having the property with the value undefined; there's a difference between calling a function with the value undefined for an argument, and leaving that argument off entirely.)
null is slightly more specific than undefined: It's a blank object reference. JavaScript is loosely typed, of course, but not all of the things JavaScript interacts with are loosely typed. If an API like the DOM in browsers needs an object reference that's blank, we use null, not undefined. And similarly, the DOM's getElementById operation returns an object reference — either a valid one (if it found the DOM element), or null (if it didn't).
Interestingly (or not), they're their own types. Which is to say, null is the only value in the Null type, and undefined is the only value in the Undefined type.
What is the difference between "==" and "==="
The only difference between them is that == will do type coercion to try to get the values to match, and === won't. So for instance "1" == 1 is true, because "1" coerces to 1. But "1" === 1 is false, because the types don't match. ("1" !== 1 is true.) The first (real) step of === is "Are the types of the operands the same?" and if the answer is "no", the result is false. If the types are the same, it does exactly what == does.
Type coercion uses quite complex rules and can have surprising results (for instance, "" == 0 is true).
More in the spec:
Abstract Equality Comparison (==, also called "loose" equality)
Strict Equality Comparison (===)
The difference is subtle.
In JavaScript an undefined variable is a variable that as never been declared, or never assigned a value. Let's say you declare var a; for instance, then a will be undefined, because it was never assigned any value.
But if you then assign a = null; then a will now be null. In JavaScript null is an object (try typeof null in a JavaScript console if you don't believe me), which means that null is a value (in fact even undefined is a value).
Example:
var a;
typeof a; # => "undefined"
a = null;
typeof null; # => "object"
This can prove useful in function arguments. You may want to have a default value, but consider null to be acceptable. In which case you may do:
function doSomething(first, second, optional) {
if (typeof optional === "undefined") {
optional = "three";
}
// do something
}
If you omit the optional parameter doSomething(1, 2) thenoptional will be the "three" string but if you pass doSomething(1, 2, null) then optional will be null.
As for the equal == and strictly equal === comparators, the first one is weakly type, while strictly equal also checks for the type of values. That means that 0 == "0" will return true; while 0 === "0" will return false, because a number is not a string.
You may use those operators to check between undefined an null. For example:
null === null # => true
undefined === undefined # => true
undefined === null # => false
undefined == null # => true
The last case is interesting, because it allows you to check if a variable is either undefined or null and nothing else:
function test(val) {
return val == null;
}
test(null); # => true
test(undefined); # => true
The spec is the place to go for full answers to these questions. Here's a summary:
For a variable x, you can:
check whether it's null by direct comparison using ===. Example: x === null
check whether it's undefined by either of two basic methods: direct comparison with undefined or typeof. For various reasons, I prefer typeof x === "undefined".
check whether it's one of null and undefined by using == and relying on the slightly arcane type coercion rules that mean x == null does exactly what you want.
The basic difference between == and === is that if the operands are of different types, === will always return false while == will convert one or both operands into the same type using rules that lead to some slightly unintuitive behaviour. If the operands are of the same type (e.g. both are strings, such as in the typeof comparison above), == and === will behave exactly the same.
More reading:
Angus Croll's Truth, Equality and JavaScript
Andrea Giammarchi's JavaScript Coercion Demystified
comp.lang.javascript FAQs: JavaScript Type-Conversion
How do I check a variable if it's null or undefined
just check if a variable has a valid value like this :
if(variable)
it will return true if variable does't contain :
null
undefined
0
false
"" (an empty string)
NaN
undefined
It means the variable is not yet intialized .
Example :
var x;
if(x){ //you can check like this
//code.
}
equals(==)
It only check value is equals not datatype .
Example :
var x = true;
var y = new Boolean(true);
x == y ; //returns true
Because it checks only value .
Strict Equals(===)
Checks the value and datatype should be same .
Example :
var x = true;
var y = new Boolean(true);
x===y; //returns false.
Because it checks the datatype x is a primitive type and y is a boolean object .
Ad 1. null is not an identifier for a property of the global object, like undefined can be
let x; // undefined
let y=null; // null
let z=3; // has value
// 'w' // is undeclared
if(!x) console.log('x is null or undefined');
if(!y) console.log('y is null or undefined');
if(!z) console.log('z is null or undefined');
try { if(w) 0 } catch(e) { console.log('w is undeclared') }
// typeof not throw exception for undelared variabels
if(typeof w === 'undefined') console.log('w is undefined');
Ad 2. The === check values and types. The == dont require same types and made implicit conversion before comparison (using .valueOf() and .toString()). Here you have all (src):
if
== (its negation !=)
=== (its negation !==)
If your (logical) check is for a negation (!) and you want to capture both JS null and undefined (as different Browsers will give you different results) you would use the less restrictive comparison:
e.g.:
var ItemID = Item.get_id();
if (ItemID != null)
{
//do stuff
}
This will capture both null and undefined
Try With Different Logic. You can use bellow code for check all four(4) condition for validation like not null, not blank, not undefined and not zero only use this code (!(!(variable))) in javascript and jquery.
function myFunction() {
var data; //The Values can be like as null, blank, undefined, zero you can test
if(!(!(data)))
{
//If data has valid value
alert("data "+data);
}
else
{
//If data has null, blank, undefined, zero etc.
alert("data is "+data);
}
}
There's quite a few JavaScript idioms that coerce between types and similar things.
! can convert anything falsey to boolean true, !! can convert anything falsey to actual boolean false, + can convert true, false, or a string representing a number into an actual number, etc.
Is there something similar that converts undefined to null?
Now I'm using ternary ? : but it would be cool to know if I'm missing a useful trick.
OK, let me contrive an example ...
function callback(value) {
return value ? format(value) : null;
}
callback is called by 3rd party code which sometimes passes undefined.
The 3rd party code can handle null being passed back, but not undefined. format() is also 3rd party and can't handle being passed either undefined or null.
Javascript now supports a null-coalescing operator: ??. It may not be production-ready (consult the support table), but it's certainly safe to use with Node or a transpiler (TypeScript, Babel, etc.).
Per MDN,
The nullish coalescing operator (??) is a logical operator that returns its right-hand side operand when its left-hand side operand is null or undefined, and otherwise returns its left-hand side operand.
Much as || can provide a "default" value when the left operand is falsey, ?? provides a "default" value if the left operand is null or undefined. You can use this to coerce undefined to null:
// OR operator can coerce 'defined' values
"value" || null; // "value"
0 || null; // null
false || null; // null
"" || null; // null
undefined || null; // null
// The null-coalescing operator will only coerce undefined or null
"value" ?? null; // "value"
0 ?? null; // 0
false ?? null; // false
"" ?? null; // ""
undefined ?? null; // null
An example based on the question:
function mustNotReturnUndefined(mightBeUndefined) { // can return null
// Substitute empty string for null or undefined
let result = processValue(mightBeUndefined ?? "");
// Substitute null for undefined
return result ?? null;
}
undefined || null - or any falsey || null - will return null
This is a fairly old question and probably my answer is a little late, but I decided for myself in the following way:
const valueOrNull = (value = null) => value;
const a = { d: '' };
valueOrNull(a.b?.c) === null; // true
valueOrNull(a.d) === ''; // true
valueOrNull() === null; // true
Any undefined value will get null as the default value;
public static replaceUndefinedWithNull(object: any) {
if (isUndefined(object)) {
return null;
}
return object;
}
If I have code that looks like this with a test for ===
var a = (b === null) ? "" : 888;
then is this the same as just placing the variable name inside () ?
var a = (b) ? "" : 888;
b === null will check if b have same type, in your case null, just checking for (b) will check for undefined, Boolean, Int, null and String values.
Basically == Just compare two variables value, and if requires it will convert datatypes implicitely.
while === will compare two variables value with it's datatype.
Consider this simple example,
0==false // true
0===false // false, because they are of a different type
1=="1" // true, auto type coercion
1==="1" // false, because they are of a different type
this is how == and === work.
in javascript we can easily cast all kinds of values to a boolean just with using them as a boolean, and there are some values which presents the false value like:
null
""
undefined
0
false
the other point is, == compares the values of object and works with valueOf() objects,
but === compare the object instances.
For example:
var MyClass = function(){};
MyClass.prototype.valueOf = function(){return 12;};
var obj = new MyClass();
console.log(obj==12);//result is true
BUT
console.log(obj===12);//result is false
the point is when you compare an object with null like:
obj === null
it would compare them as 2 different objects, but if you do it like:
obj == null; //better way to check the value
it would compare the values:
var myobj = undefined;
console.log(myobj==null);//result is true
But instead of all these lines of codes if you really want a Boolean value you can do it like:
obj = !!obj;//this is something like a toBoolean method.
No, it is not the same.
=== means strict equality, the left hand side and right hand side need to be equal in both type and value.
using the if (a) construct, a is checked to be truthy or falsy. Falsy values are for example "" (string), 0 (number), undefined and null.
if (a) is almost the same as if (a !== null && a !== undefined && a !== "" && a !== 0)
I am using the following:
$scope.option.selectedSubject != null && !isNaN($scope.option.selectedSubject)
Can someone tell me if there is another way to check if a variable is a valid defined number? Is there some way I can do this with just one check or how can I create a function to do this check and then call that ?
maybe this function might help you :
function isANumber(x) {
return ((+x)===x);
}
This might be useful to know: A variable can only be null when somewhere in your script it's being assigned, it will never be null by default.
var foo; // undefined
foo = null;
// null could be returned by a function too, which is the most common use of null
As zzzzBov stated in his comment, "isNaN will check if the numeric representation of the value is NaN. this means that isNaN('500') is false, while isNaN('foo') is true."
As to answer your question, check this table:
!isNaN(undefined); // false
!isNaN(null); // true
!isNaN(); // false
!isNaN(''); // true <= Watch out for this one !
!isNaN('test'); // false
!isNaN('10'); // true
!isNaN(10); // true
If you want to make sure it's a number, you should use typeof, then if this is a string, check if it has a length. Wrapping this all in a function would create something like:
function isNumber (num) {
// Return false if num is null or an empty string
if (num === null || (typeof num === "string" && num.length === 0)) {
return false;
}
return !isNaN(num);
}
isNumber(undefined); // false
isNumber(null); // false
isNumber(); // false
isNumber(''); // false
isNumber('test'); // false
isNumber('10'); // true
isNumber(10); // true
This would do the trick if you care only about numeric presentation.
!isNaN($scope.option.selectedSubject + "")
Notice the + ""
Other than creating a function, is there a shorter way to check if a value is undefined,null or false only in JavaScript?
The below if statement is equivalent to if(val===null && val===undefined val===false)
The code works fine, I'm looking for a shorter equivalent.
if(val==null || val===false){
;
}
Above val==null evaluates to true both when val=undefined or val=null.
I was thinking maybe using bitwise operators, or some other trickery.
Well, you can always "give up" :)
function b(val){
return (val==null || val===false);
}
The best way to do it I think is:
if(val != true){
//do something
}
This will be true if val is false, NaN, or undefined.
I think what you're looking for is !!val==false which can be turned to !val (even shorter):
You see:
function checkValue(value) {
console.log(!!value);
}
checkValue(); // false
checkValue(null); // false
checkValue(undefined); // false
checkValue(false); // false
checkValue(""); // false
checkValue(true); // true
checkValue({}); // true
checkValue("any string"); // true
That works by flipping the value by using the ! operator.
If you flip null once for example like so :
console.log(!null) // that would output --> true
If you flip it twice like so :
console.log(!!null) // that would output --> false
Same with undefined or false.
Your code:
if(val==null || val===false){
;
}
would then become:
if(!val) {
;
}
That would work for all cases even when there's a string but it's length is zero.
Now if you want it to also work for the number 0 (which would become false if it was double flipped) then your if would become:
if(!val && val !== 0) {
// code runs only when val == null, undefined, false, or empty string ""
}
One way to do it is like that:
var acceptable = {"undefined": 1, "boolean": 1, "object": 1};
if(!val && acceptable[typeof val]){
// ...
}
I think it minimizes the number of operations given your restrictions making the check fast.
Another solution:
Based on the document, Boolean object will return true if the value is not 0, undefined, null, etc. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean
If value is omitted or is 0, -0, null, false, NaN, undefined, or the empty string (""), the object has an initial value of false.
So
if(Boolean(val))
{
//executable...
}
only shortcut for something like this that I know of is
var val;
(val==null || val===false) ? false: true;
Boolean(val) === false. This worked for me to check if value was falsely.
Using ? is much cleaner.
var ? function_if_exists() : function_if_doesnt_exist();
Try like Below
var Boolify = require('node-boolify').Boolify;
if (!Boolify(val)) {
//your instruction
}
Refer node-boolify