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.
Related
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));
The following javascript code is getting giving undefined as the final output. But as far as I know the OR ' || ' operator will stop the evaluation as soon as it gets "true". But in this block of code it is trying to evaluate the remaining conditions even though it gets true on the first expression.
field = {
ipaddr: "0.0.0.0",
nodePresentInTopo: false
}
var bestName = field.ipaddr || (field.ip6addr && field.ip6addr != '::') ? field.ip6addr : undefined || field.sysid;
Here bestName always evalueavtes to undefined but why? As it is getting the value at field.ipaddr i.e 0.0.0.0
Please explain the logic.
In one word: operator precedence.
Yes, || short-circuits and doesn't evaluate the second half of the expression used as condition in the ternary operator.
field.ipaddr || (field.ip6addr && field.ip6addr != '::') ? .. : ..
Evaluates to:
'0.0.0.0' ? .. : ..
Which evaluates to true and then evaluates the true branch of the ternary operator:
field.ip6addr
If you want a different logical grouping, use parentheses:
field.ipaddr || (.. ? .. : ..);
I'm assuming you know that you've written field.ipaddr instead of fields.ipaddr. Probably for testing purposes. If the last part of the expression is your problem, write it like so:
(undefined || fields.sysid);
I don't think so is there any property with name ip6addr in current object?
var bestName = (field.ipaddr || (field.ip6addr && field.ip6addr != '::') ? field.ipaddr : undefined || field.sysid);
undefined
Either you should add ip6addr in current object or replace with appropriate property
In the condition portion of the following ternary statement, does playlist.length equal playlist.length >= 1 ?
var playlist = ["video1", "video2", "video3", "video4", "video5"];
// some code here
alert ((playlist.length) ?
playlist.length + "video(s) remain in the playlist: " + playlist.join (", ") + "."
: "No videos remain in the playlist");
Likewise, in the following snippet of code, does ! playlist.length equal playlist.length === 0 ?
alert ((! playlist.length) ?
"No videos in the playlist."
: playlist.length + " video(s) remain in the playlist: " + playlist.join(", ") + ".");
This is the first time I've seen an example where the condition portion of a ternary or if statement does not include such a notation as === or >=. So I'm not sure how to interpret this.
0 is implicitly converted to false in boolean comparisons in JavaScript. So when the length is 0, that is false. Conversely, any other number is implicitly converted to true in boolean comparisons in JavaScript. So when the length is anything but 0 it is true.
An easy test is to use !! to see the "truthy" value
!!1 === true
!!0 === false
!!6 === true
The part to the left of the ? is simply evaluated for "truthiness". The value 0 is "falsy" so evaluates as false for the purposes of the test. Numeric values other than 0 are "truish" and therefore for this purpose evaluate to true.
All other behaviors of the ternary are the same.
The === and !== simply add the additional constraint that the L-value and R-value must also be the same type.
The two are very similar: !playlist.length and playlist.length === 0.
However, they are not exacty the same. In fact, here:
var playlist1 = [];
var playlist2 = {};
!playlist1.length // true
!playlist2.length // true
playlist1.length === 0 // true
playlist1.length === 0 // false
In that sense !playlist.length also can be used on all kinds of objects, not just arrays.
In any case, when using this on an array, it is a way to check if the array is empty, and works as you have suggested, the same as playlist.length === 0.
In javascript 0 equals false, and any other number value equals true, but if you use === it compare value types too.
The following is common code floating around online that checks if cookies are enabled in a particular browser:
var cookieEnabled = (window.navigator.cookieEnabled) ? true : false;
if (typeof navigator.cookieEnabled == "undefined" && !cookieEnabled) {
document.cookie = "testcookie"
cookieEnabled = (document.cookie.indexOf("testcookie") != -1) ? true : false
}
if (!cookieEnabled) {
// do some work
}
Why are the first and fifth lines ternary statements? Does
var cookieEnabled = (window.navigator.cookieEnabled) ? true : false;
catch some case that the following wouldn't?
var cookieEnabled = (window.navigator.cookieEnabled);
The same goes for the fifth line.
The ternary statement at the first line is useful in that it coverts a possible non-boolean value into a boolean one. Consider the following code
window.navigator.cookieEnabled = "evil people do this";
The above is legal and as the value says evil people do do this. Without the ternary statement the following code wouldn't execute as expected
if (cookiesEnabled === false) {
// ...
}
To be precise:
(window.navigator.cookieEnabled) ? true : false
is equivalent to:
!!window.navigator.cookieEnabled
However:
(document.cookie.indexOf("testcookie") != -1) ? true : false
can be simply replaced by:
document.cookie.indexOf("testcookie") != -1
Finally:
cookieEnabled == false
can be changed to:
!cookieEnabled
So what's the problem with the first case? In JavaScript non-zero numbers, non-empty strings, etc. evaluate to true. So if(window.navigator.cookieEnabled) passes for cookieEnabled being equal to "foo" and 42 as well. If you really want to have a variebale of boolean type, you must negate it twice.
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.