simplify number validation in if statement JavaScript - javascript

I am validating my time in this way
if (
timeInMins != 0 &&
timeInMins != "0" &&
timeInMins != undefined &&
timeInMins != "undefined" &&
timeInMins != null &&
timeInMins != "" &&
!isNaN(timeInMins)
) {
timeInMinsCumulative += parseFloat(timeInMins);
}
Is there any way to make this ugly if-check to sophisticated code?

There are 6 falsy values in javascript: undefined, null, NaN, 0, "" (empty string), and false of course.
So, you can just write
if (timeInMins && timeInMin !== '0') {
timeInMinsCumulative += parseFloat(timeInMins);
}

This uses the coercion behavior of JavaScript and the logical AND operator to simplify your code. The following is very nearly equivalent to your code, but it will also guard against the arguments false and 0n.
if (timeInMins &&
timeInMins !== '0' &&
timeInMins !== 'undefined') {
// whatever
}
Questions for you: do you really expect to ever get the string 'undefined' passed to you? Why do you want to guard against '0' being sent to parseFloat? Are you sure parseInt is not what you want?

It seems you want to check if timeInMins is precise Number type or not.
function isValidNumber(num) {
return typeof num === "number" && !isNaN(num);
}
console.log(isValidNumber(""));
console.log(isValidNumber(undefined));
console.log(isValidNumber(NaN));
console.log(isValidNumber("undefined"));
console.log(isValidNumber(true));
console.log(isValidNumber(false));
console.log(isValidNumber(0));
console.log(isValidNumber("0"));
console.log(isValidNumber(1.234));

Related

Improve condition code

I've the following code
var oDataEn = aData[0][aProperties[0].split('/')[0]];
if (!(oDataEn != null && oDataEn.results && oDataEn.results.length > 0)) {
...
else
...
This is working OK except when
aData[0] = 'undefined'
my question is if there a better way to write it instead of just adding before
if(aData[0] != null)
{
var oDataEn = aData[0][aProperties[0].split('/')[0]];
}
I dont want to have two if's if possible...
Start with a ternary - I assume aData[0] may be falsy (null, undefined, 0 or ""):
var oDataEn = aData[0]?aData[0][aProperties[0].split('/')[0]]:null;
if (oDataEn && oDataEn.results && oDataEn.results.length > 0) {
if(aData[0] === undefined){}
is the best way so far I know.
As per your comment
if(typeof aData[0] != 'undefined' /*&& other if statements*/){}
So it will not process if it is undefined.
By using ternary operator u can do this. Ternary operator will reduce the line of codes only.
var oDataEn = aData[0] === undefined ? '' : aData[0][aProperties[0].split('/')[0]];

function not executing on comparison of two arrays

I am trying to get a comparison operator to work, without success. The operator compares two arrays to ensure they are identical.
if (($(array_1).not($(array_2)).length === 0 && $(array_2).not($(array_1)).length === 0)) {
alert("all matches dropped");
}
The code works of course with 'true' in place of the comparison.
if (true) {
alert("all matches dropped");
}
The strange part is that the comparison returns 'true' when entered into the console:
console.log($(array_1).not($(array_2)).length === 0 && $(array_2).not($(array_1)).length === 0)
----> true
Any ideas what may be wrong? Thanks.
It should be:
if($(array_1).not(array_2).length === 0 && $(array_2).not(array_1).length === 0)
Instead of:
if (($(array_1).not($(array_2)).length === 0 && $(array_2).not($(array_1)).length === 0))
Here $(array_1).not(array_2).length and ($(array_1).not($(array_2)).length both are not the same thing.

how do i make this javascript logic + syntax (very simple)

Why I am getting true all the time?
var _template_id = "";
if (_template_id != '0' || _template_id!="") {
alert("true")
}else{
alert("false")
}
or even if i set _template_id="0", it still turns out as true...
Because you're asking if _template_id isn't equal to "0" OR isn't equal to "". One of those will always be true.
Proof: Given your statement of (_template_id != '0' || _template_id!=""), let's suppose that the first part is false. Therefore _template_id == '0' is true, and hence _template_id != "" is true, so overall the statement evaluates to true.
If, on the other hand, the first part is true, then clearly the whole thing evaluates to true again.
Therefore, the statement is always true.
You want && not ||.
It must always be true because "0" != "", so one or the other is always true.
a != b || a != c is always true when b and c are different.
What you want here is probably to use
if (!(_template_id == '0' || _template_id =="")) {
alert("true")
Then if you set _template_id="0" you would get false as desired.
You probably want
!(_template_id == '0' || _template_id == "")
If _template_id is neither 0 nor ''.
This is equivalent (thanks to De Morgan's laws) to:
_template_id != '0' && _template_id != ""
Where are you trying to change the value of _template_id ? I will always be true if you assign "" and then ask if its '0' or "" then true.
You are logically going wrong.
Either use == and ¦¦
Or
Use != and &&
It will result the same in both cases and your condition will be true as well.

JavaScript comparison issues

I need this comparison in my javascript to work.
if ((q2 != '' && correct2 != 'True') || (q2 != '' && correct2 != 'true') || (q2 != '' && correct2 != 'false') || (q2 != '' && correct2 != 'False'))
{
alert("You must enter true or false.");
}
q2 and correct2 are textboxes and if q2 has something in it and correct2 doesn't equal true, True, false, or False then I want the message box pops up. My code is not working. If I put true or false in the blank the error message still shows up.
EDIT
I have found how to make it work. Instead of putting || between the comparisons I put && and it works perfectly.
To get the value of a text input, do something like
var q2Value = q2.value;
For the conditionals, || is or, not or, and everytime you do a comparison you need 2 values/variables
(correct2 !== 'True ) || (correct2 !== 'true')...
You can see I wrapped the comparisons in parenthesis so its perfectly clear what should be compared to what, even if it isn't strictly necessary.
Since you need q2 to be correct before comparing the other condition, you can use a nifty feature called short-circuiting. Basically, && only proceeds if the first comparison is truthy, so you would do
(qa2 !== '') && (the rest)
Note that if a user doesn't enter the value at all, when you get the value of the text field it will be undefined (I think), not '''. So you should really just do
qa2 && (...)
Basically null, undefined, and '' are all falsy in javascript, so if qa2 is any of those values, the second part of the and won't be processed.
This should work.
if ((q2 != '' && correct2 != 'True') || (q2 != '' && correct2 != 'true') || (q2 != '' && correct2 != 'false') || (q2 != '' && correct2 != 'False'))
{
alert("You must enter true or false.");
}
try this
if(q2 !== '' && !(correct2 == 'true') && !(correct2 == 'True') && !(correct2 == 'False') && !(correct2 == 'false'))
{
alert("You must enter true or false.")
};

Javascript Empty String Comparison

I don't understand why one scenario evaluates false and the other true.
Scenario 1:
> '' == ''
true
Scenario 2:
> '' == ('' || undefined)
false
Is scenario 2 not asking if (empty string) is equal to: (empty string) OR undefined?
I'm sure I'm missing something fundamental here, which is really what I'm trying to figure out. I can easily code around this, but I'd like to learn why it's happening... for next time, ya know?
'' == ( '' || undefined )
Is not the same as
( '' == '' ) || ( '' == undefined )
It's more along the lines of:
var foo = '' || undefined; // Results in undefined
And then comparing foo to an empty string:
foo == ''; // undefined == '' will result in false
Explanation
The logical || is a short-circuiting operator. If the argument to its left is truthy, the argument to the right is not even evaluated. In JavaScript, '' is not considered to be truthy:
if ( '' ) console.log( 'Empty Strings are True?' );
As such undefined is returned and compared against an empty string. When you perform this logic within a the parenthesis, the '' and the undefined don't know about the impending equality check that is waiting to happen - they just want to know which of them is going to survive this evaluation.
Let's break it:
'' == ('' || undefined) // return "undefined"
'' == undefined // false
|| return the first true value or the last value.
DEMO
You want this:
'' == undefined || '' == false
undefined is == only to null, and not to all other "falsy" values:
0
"" - empty string
NaN
false
try '' == '' || '' == undefined
As in almost all programming languages, the expressions at both sides of an operator must evaluate to a valid operand. || is logical OR operator which is used to evaluate a pair of boolean operands.

Categories