Javascript if statement needs refactoring due to bad data from my database.
I want a nicer way of doing this if statement:
if (typeof value === undefined || value === null || value === "" || value === 0) {
return false;
}
Is there a shorter way?
I look forward to your suggestions.
Is there a shorter way?
Only slightly:
if (value == null || value === "" || value === 0) {
...because both undefined and null are == null (and nothing else is).
Alternately, in ES2015 you could use a Set of values you want to filter:
let badValues = new Set([undefined, null, "", 0]);
then
if (badValues.has(value)) {
If you also are happy filtering out false and NaN, then you can just use
if (!value) { // Does more values than your question asks for, see note above
Note that your first condition is wrong: If you use typeof value then undefined must be in quotes, because typeof always returns a string.
You could even do something like this:
return Boolean(value);
Note that:
!!null === false
!!"" === false
!!0 === false
!!undefined === false
You can just write:
if (!value || !value.length) {return false}
if (!value) return false;
proof - >
console.log(!undefined, !null, !"", !0);
returns -> true true true true
console.log(!100, !"hello", !"0", !"false", !"true");
returns -> false false false false false
Javascript automatically transform into boolean other variables types in if statement, you can do something like this:
if (!value || !value.length) {
return false;
}
undefined, null and 0 are transformed into "false", meanwhile with .length, if it is 0 you will still have false, otherwise another number will be true.
Cheers
EDIT
for avoiding the object {length:0} to be parsed as empty, you can add:
if (!value || ((value instanceof Array || typeof value === 'string') && !value.length)) {
return false;
}
Related
In javascript I need to check for a value in an if statement if it exists. The thing is 0 can be one of the accepted values. so when I do
if(!val) {
return true
}
return false
The thing is Javascript evaluates !0 = false
here are test cases what I want:
val = 0 // true
val = 91 // true
val = null // false
val = undefined = false
Basically check check for null but include 0. Not sure how to do this :/
For type check you have:
typeOf:
// note: typeof [] = object and typeof {} = object
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof
Array.isArray():
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray
isNaN()/Number.isNaN():
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/isNaN
Is one of those what you're looking for?
!0 = true // in js. just tried it on MDN
Check for undefined and null:
function isValNumber(val) {
if (val === undefined || val === null) {
return false
}
return true
}
console.log(isValNumber(0))
console.log(isValNumber(91))
console.log(isValNumber(null))
console.log(isValNumber(undefined))
I think you need to be checking for null & undefined in your conditional statement. That way, anything that is 0 or greater will return true. You also need to check the typeOf() for undefined because you undefined is not the value of the variable.
if (typeof(val) != 'undefined' && val != null && !(val < 0)){
return true;
}else{
return false;
}
0 is falsy so !0 is true in JavaScript, but to meet your test cases I think you want truthy values to return true, and you need to handle the special case for 0. One way to do it:
function test(val) {
if (val || val === 0) {
return true
}
return false
}
console.log(test(0));
console.log(test(91));
console.log(test(null));
console.log(test(undefined));
You could also leverage Javascript's weak equivalence operator and use != null which covers null and undefined as below:
function test(val) {
if (val != null) {
return true
}
return false
}
console.log(test(0));
console.log(test(91));
console.log(test(null));
console.log(test(undefined));
Since we all know null is evaluated as false, how could I write "is null or true" in Javascript?
I have tried:
function isNullOrTrue(nullableBool){
return !(nullableBool != null && nullableBool != true);
}
Is there a better way to do this?
If the three possible inputs are only null, true and false, you can use
return nullableBool !== false
but explicitly listing the matching values isn't bad for readability either
return v === null || v === true
Using === instead of == isn't actually necessary here, as null != false (whereas Boolean(null) == false), but it might help for clarity if you're not familiar with the loose equality rules.
The elegant solution to is null or true is to use nullish coalescing operator
return nullableBool ?? true
It will return true if nullableBool is either null or undefined. Otherwise, it will return the value of nullableBool. If you only want to return true or false, then you can use double bang:
return !!(nullableBool ?? true)
Now, it will return true if nullableBool is either null, undefined or truthy value. Otherwise, return false.
I have this code:
if (window.content.document.getElementById("error-msg") != null )
{
if (window.content.document.getElementById("error-msg").offsetParent !== null)
{
...
}
}
Can it be written in one if statement?
I tried the following...
if ( (window.content.document.getElementById("error-msg") != null) || (window.content.document.getElementById("error-msg").offsetParent !== null) ) {}
But, it didn't work, and produces an error:
TypeError: window.content.document.getElementById(...) is null
The common idiom is to use the && operator like this
var errorMsg = window.content.document.getElementById("error-msg");
if (errorMsg && errorMsg.offsetParent) {
...
}
Here, JavaScript will evaluate errorMsg first and if it is Truthy, then it will evaluate the errorMsg.offsetParent part. The condition will be satisfied only if both the expressions in && are Truthy.
Note: The Truthy evaluation will return false, if the expression being tested is 0, false etc (See the list of Falsy values here). So, if you want to test if they are not null, just write that explicitly, like this
if (errorMsg !== null && errorMsg.offsetParent !== null) {
...
}
On the other hand, the || operator will evaluate the second operator only if the first expression is Falsy. In your case, if
(window.content.document.getElementById("error-msg") != null)
is true, it means that getElementById("error-msg") returns null. Since the first expression is evaluated to be Truthy, it evaluates the other expression and it effectively tries to check
null.offsetParent !== null
That is why it fails.
Maybe you want to use &&
if (a != null && b != null) {
// Do something.
}
undefined and null are falsy in javascript but,
var n = null;
if(n===false){
console.log('null');
} else{
console.log('has value');
}
but it returns 'has value' when tried in console, why not 'null' ?
To solve your problem:
You can use not operator(!):
var n = null;
if(!n){ //if n is undefined, null or false
console.log('null');
} else{
console.log('has value');
}
// logs null
To answer your question:
It is considered falsy or truthy for Boolean. So if you use like this:
var n = Boolean(null);
if(n===false){
console.log('null');
} else{
console.log('has value');
}
//you'll be logged null
You can check for falsy values using
var n = null;
if (!n) {
console.log('null');
} else {
console.log('has value');
}
Demo: Fiddle
Or check for truthiness like
var n = null;
if (n) { //true if n is truthy
console.log('has value');
} else {
console.log('null');
}
Demo: Fiddle
A value being "falsy" means that the result of converting it to a Boolean is false:
Boolean(null) // false
Boolean(undefined) // false
// but
Boolean("0") // true
This is very different from comparing it against a Boolean:
null == false // not equal, null == true is not equal either
undefined == false // not equal, undefined == true is not equal either
// but
"0" == true // not equal, however, `"0" == false` is equal
Since you are using strict comparison, the case is even simpler: the strict equality comparison operator returns false if operands are not of the same data type. null is of type Null and false is of type Boolean.
But even if you used loose comparison, the abstract equality algorithm defines that only null and undefined are equal to each other.
Depending on what exactly you want to test for, you have a couple of options:
if (!value) // true for all falsy values
if (value == null) // true for null and undefined
if (value === null) // true for null
In general you should always prefer strict comparison because JS' type conversion rules can be surprising. One of the exceptions is comparing a value against null, since loose comparison also catches undefined.
=== checks for identity - the exact same type and value. So null !== false firstly because they are not the same type, thus will not match when using ===.
If you just want to check for any falsey value, then check with:
if (!n)
If you want to specifically check for null, then check for null like this:
if (n === null)
Why does the && operator return the last value (if the statement is true)?
("Dog" == ("Cat" || "Dog")) // false
("Dog" == (false || "Dog")) // true
("Dog" == ("Cat" && "Dog")) // true
("Cat" && true) // true
(false && "Dog") // false
("Cat" && "Dog") // Dog
("Cat" && "Dog" && true) // true
(false && "Dog" && true) // false
("Cat" && "Dog" || false); // Dog
Fiddle
Logical Operators - && (MDN)
Returns expr1 if it can be converted to false; otherwise, returns expr2. Thus, when used with Boolean values, && returns true if both
operands are true; otherwise, returns false.
For your expression "Cat" && "Dog" , the first expression "Cat" can't be converted to false or a boolean value, hence it returns "Dog"
Think of && in JavaScript like this (based on ToBool from the es5 spec)
function ToBool(x) {
if (x !== undefined)
if (x !== null)
if (x !== false)
if (x !== 0)
if (x === x) // not is NaN
if (x !== '')
return true;
return false;
}
// pseudo-JavaScript
function &&(lhs, rhs) { // lhs && rhs
if (ToBool(lhs)) return rhs;
return lhs;
}
Now you can see that ToBool("Cat") is true so && will give rhs which is "Dog", then === is doing "Dog" === "Dog", which means the line gives true.
For completeness, the || operator can be thought of as
// pseudo-JavaScript
function ||(lhs, rhs) { // lhs || rhs
if (ToBool(lhs)) return lhs;
return rhs;
}
Why does the && operator return the last value?
Because that's what it does. In other languages, the && operator returns the boolean true or false. In Javascript, it returns the first or second operand, which is just as well since those values themselves are "truthy" or "falsey" already.
Hence 'Cat' && 'Dog' results in the value 'Dog', which is equal to 'Dog'.
Because you asked if true === (true && true). If you use a non Boolean in a Boolean operation, javascript will convert to Boolean. Non empty strings are "true" so it returns correct.
I'm guessing the language designers wanted to enable users to use the || operator as a "coalesce" operator, in the style of e.g. the "null coalesce" operator ?? in C#.
In other words, if you want a default value, you can use the following idiom:
var x = input || "default";
//x will be equal to input, unless input is falsey,
//then x will be equal to "default"