Refactoring repeated if statement within if else block - javascript

I have this if blocks where i have to test within on the same thing in both blocks :
if (download !== 'true') {
if(index == undefined){
res.json(req.doc);
}else{
res.json(index)
}
} else {
if(index == undefined){
exports.download(res, req.doc);
}else{
res.json(index)
}
}
Is there a way to refactor it in a way in which i wouldn't repeat the same thing ?

Since you do the same thing in both branches when index == undefined is false, just do that test first and invert it:
if (index != undefined) {
res.json(index);
} else if (download !== 'true') {
res.json(req.doc);
} else {
exports.download(res, req.doc);
}
Side notes:
== undefined and != undefined will treat undefined and null the same way. If you don't want your conditions to treat null like undefined, use === and !==.
It's slightly odd that download is a string, although of course that does happen sometimes. If download is actually a boolean, then !== 'true' will always be true (because no boolean is ever strictly equal to a string). If it's a boolean, use if (download) or if (!download) rather than === true or !== true. If it is a string, beware of whitespace at the beginning or end and capitalization (' true' !== 'true' is true because of the space; 'True' !== 'true' is true because of the capital T). FWIW.

Related

How to check if variable is not falsy but 0 passes in Javascript

Is there an elegant way to check if variable is NOT falsy but in case of 0 it passes. The issue with this way of verifying
if(var !== undefined && var !== null)
is that it's long and doesn't cover all cases like undecalred or NaN. I'm also using typescript and declare it as optional number.
You can do exactly what your first sentence asks:
if (!x && x !== 0)
means literally "if x is falsy and x is not 0".
Also the == and != comparison operators explicitly consider null and undefined to be equal, so
if (x != null)
is true for both null and undefined. (That's !=, not !==.)
function Check(input) {
if (!input && input!==0){
return "falsy";
}
else if (input === 0){
return "zero";
}
}
console.log(Check(0));
console.log(Check(false))

Javascript if statement needs refactoring due to bad data

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;
}

How to skip the second part of (JavaScript if statement) if the first part is 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.
}

difference between assignments given to a variable?

false
0
null
undefined
empty string
I use them,but I am still unaware of the marginal difference each prospect in the above list have.
I mostly use 0,false.But I have come across many scripts that uses undefined ,empty string.
I want to know the exact differnce between them.
I know its a silly question,but would be great If i get a small conscise answer.
It's called "truthy and falsy values" if you want to know how to refer to it.
Here is a link to explain the answer to your question: http://www.sitepoint.com/javascript-truthy-falsy/
(Keep in mind when reading the link at the beginning that !!(value) forces the value to be either true or false)
The type is the difference.
false is a boolean, 0 is a number, null is an object, undefined is undefined, and '' is a string.
You pick the type based on what it is being used as. For example:
// There is nothing wrong with this block of code
var num_cats = 7;
if(num_cats){
// num_cats is truthy
}
// This block works but it could be made more clear
var has_cat = num_cats;
if(has_cat){
// This would work, but it doesn't make sense. As a developer I would
// expect that has_cat should be either true or false, not 7.
// One way to convert the number to a boolean would be:
has_cat = !!num_cats
}
The two most confusing falsey values are probably null and undefined.
null basically means that the variable exists, but it's value is unknown.
undefined means that the variable doesn't exist (although a variable can be explicity set to undefined like var x = undefined; and then the variable x exists but it is explicitly not being defined which means that you can treat it as though it doesn't exist.
The list you have are 5 of the 6 "falsy" values in javascript. If you add "NaN" to that, you would have all the falsy values in javascript. So the complete "falsy" list is
1)0
2)""
3)false
4)undefined
5)null and
6)NaN
When used in a "if" statement, these all behave the same way so
if(0)
if("")
if(false)
if(undefined)
if(null) and
if(NaN) would behave the same
You asked for a short concise answer but I think the best way is just showing how it works with some basic test. Apologies for the long answer
//Checking if all the "falsy" values evaluate the same way in a "if" statement
console.log("Checking if(0)");
if(0) {
console.log(" if(0) Will not be reached");
}
console.log('Checking if("")');
if("") {
console.log(' if("") Will not be reached');
}
console.log("Checking if(undefined)");
if(undefined) {
console.log("if(undefined) Will not be reached");
}
console.log("Checking if(null)");
if(null) {
console.log("if(null) Will not be reached");
}
console.log("Checking if(Nan)");
if(NaN) {
console.log("if(NaN) Will not be reached");
}
console.log("Checking if(false)");
if(false) {
console.log("if(false) Will not be reached");
}
//Checking if all the falsy values are equal(==) to each other in a if statement
if(0 == "") {
console.log('if(0 == "") is true');
}
if(0 == false) {
console.log("if(0 == false) is true");
}
if("" == false) {
console.log('if("" == false) is true');
}
if(0 == undefined) {
console.log("if(0 == undefined) Will not be reached");
}
if("" == null) {
console.log('if("" == null) Will not be reached');
}
if(undefined == null) {
console.log("if(undefined == null) is true");
}
if(NaN == "") {
console.log('if(NaN == "") Will not be reached');
}
//Checking for strictly equality between false and falsy values
if(undefined === false) {
console.log("Will not be reached");
}
if(null === false) {
console.log("Will not be reached");
}
if(undefined ===false) {
console.log("Will not be reached");
}
if(0 === false) {
console.log("Will not be reached");
}
if("" === false) {
console.log("Will not be reached");
}
if(NaN === false) {
console.log("Will not be reached");
}
What this means that though these "falsy" values might be used in a "if" statement interchangeably, they all are not equal(==) to each other(particular the set of 0,"" and false with the other three). If a stricter equals(====) is used, none of these would be equal to false, hence perhaps the classification "falsy" instead of false.
Only two of the values you've mentioned are what I would call designated "special values".
null - In most cases this is equivalent to not applicable.
undefined - The implicit version of null
An example for both:
function findByTitle(arr, title)
{
for (var i = 0; i < arr.length; ++i) {
if (arr[i].title === title) {
return arr[i];
}
}
return null;
}
The return value of null indicates that the record could not be found, otherwise it's an object.
function increment(x, by)
{
return x + (by || 1); // by may be undefined
}
increment(4); // 5
In this case, the by argument is not passed, so JavaScript passes it as undefined implicitly. I wouldn't recommend assigning this to a variable though; rather, I would use null.
The other values you have mentioned are not particularly special; they can be used as a starting value, such as building a string value or calculating a sum, but they're not special in their own right.
"" is a string
false is a boolean
0 and NaN are numbers

How do i compare against an empty variable?

If I set a variable to 0, I get the weird behavior that a comparison to "" (empty) is true. How do I check that the variable is really empty?
tmp = 0;
if ( tmp != "")
{
//do something - This is where the code goes.
}
else
{
//isEmpty - I would expect to be here
}
Use strict comparison operators
=== and !==
With == and != (called abstract comparison operators),
If the two operands are not of the same type, JavaScript attempts to
convert the operands to an appropriate type for the comparison.
If by empty, you want to check if the variable hasn't been defined, use:
if (typeof tmp !== "undefined") {
// it exists!
}
What do you mean by empty variable? If you mean an empty string, then you should use !== to check it.
if (tmp !== "")
JavaScript implicitly converts values to other types. To check type also, use the !== operator:
if ( tmp !== "")
In JavaScript everything except 0, NaN, undefined, false and null are considered to be false. "" is considered as true.
if (tmp) {
}
Above if will be executed if variable contains any value other than 0, NaN, undefined, false and null.
If tmp is a string then you can use the following code:
if (tmp !== "") {
}
=== and !== operators compare without doing type-conversion.

Categories