Javascript Empty String Comparison - javascript

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.

Related

simplify number validation in if statement 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));

In Javascript why, console.log(0 && 0 === 0); returns 0 instead of true? [duplicate]

Why do these logical operators return an object and not a boolean?
var _ = (obj.fn && obj.fn() ) || obj._ || ( obj._ = {} );
var _ = obj && obj._;
I want to understand why it returns result of obj.fn() (if it is defined) OR obj._ but not boolean result.
In JavaScript, both || and && are logical short-circuit operators that return the first fully-determined “logical value” when evaluated from left to right.
In expression X || Y, X is first evaluated, and interpreted as a boolean value. If this boolean value is “true”, then it is returned. And Y is not evaluated. (Because it doesn’t matter whether Y is true or Y is false, X || Y has been fully determined.) That is the short-circuit part.
If this boolean value is “false”, then we still don’t know if X || Y is true or false until we evaluate Y, and interpret it as a boolean value as well. So then Y gets returned.
And && does the same, except it stops evaluating if the first argument is false.
The first tricky part is that when an expression is evaluated as “true”, then the expression itself is returned. Which counts as "true" in logical expressions, but you can also use it. So this is why you are seeing actual values being returned.
The second tricky part is that when an expression is evaluated as “false”, then in JS 1.0 and 1.1 the system would return a boolean value of “false”; whereas in JS 1.2 on it returns the actual value of the expression.
In JS false, 0, -0, "", null, undefined, NaN and document.all all count as false.
Here I am of course quoting logical values for discussion’s sake. Of course, the literal string "false" is not the same as the value false, and is therefore true.
In the simplest terms:
The || operator returns the first truthy value, and if none are truthy, it returns the last value (which is a falsy value).
The && operator returns the first falsy value, and if none are falsy, it return the last value (which is a truthy value).
It's really that simple. Experiment in your console to see for yourself.
console.log("" && "Dog"); // ""
console.log("Cat" && "Dog"); // "Dog"
console.log("" || "Dog"); // "Dog"
console.log("Cat" || "Dog"); // "Cat"
var _ = ((obj.fn && obj.fn() ) || obj._ || ( obj._ == {/* something */}))? true: false
will return boolean.
UPDATE
Note that this is based on my testing. I am not to be fully relied upon.
It is an expression that does not assign true or false value. Rather it assigns the calculated value.
Let's have a look at this expression.
An example expression:
var a = 1 || 2;
// a = 1
// it's because a will take the value (which is not null) from left
var a = 0 || 2;
// so for this a=2; //its because the closest is 2 (which is not null)
var a = 0 || 2 || 1; //here also a = 2;
Your expression:
var _ = (obj.fn && obj.fn() ) || obj._ || ( obj._ = {} );
// _ = closest of the expression which is not null
// in your case it must be (obj.fn && obj.fn())
// so you are gettig this
Another expression:
var a = 1 && 2;
// a = 2
var a = 1 && 2 && 3;
// a = 3 //for && operator it will take the fartest value
// as long as every expression is true
var a = 0 && 2 && 3;
// a = 0
Another expression:
var _ = obj && obj._;
// _ = obj._
In most programming languages, the && and || operators returns boolean. In JavaScript it's different.
OR Operator:
It returns the value of the first operand that validates as true (if any), otherwise it returns the value of the last operand (even if it validates as false).
Example 1:
var a = 0 || 1 || 2 || 3;
^ ^ ^ ^
f t t t
^
first operand that validates as true
so, a = 1
Example 2:
var a = 0 || false || null || '';
^ ^ ^ ^
f f f f
^
no operand validates as true,
so, a = ''
AND Operator:
It returns the value of the last operand that validates as true (if all conditions validates as true), otherwise it returns the value of the first operand that validates as false.
Example 1:
var a = 1 && 2 && 3 && 4;
^ ^ ^ ^
t t t t
^
last operand that validates as true
so, a = 4
Example 2:
var a = 2 && '' && 3 && null;
^ ^ ^ ^
t f t f
^
return first operand that validates as false,
so, a = ''
Conclusion:
If you want JavaScript to act the same way how other programming languages work, use Boolean() function, like this:
var a = Boolean(1 || 2 || 3);// a = true
You should think of the short-circuit operators as conditionals rather than logical operators.
x || y roughly corresponds to:
if ( x ) { return x; } else { return y; }
and x && y roughly corresponds to:
if ( x ) { return y; } else { return x; }
Given this, the result is perfectly understandable.
From MDN documentation:
Logical operators are typically used with Boolean (logical) values. When they are, they return a Boolean value. However, the && and || operators actually return the value of one of the specified operands, so if these operators are used with non-Boolean values, they will return a non-Boolean value.
And here's the table with the returned values of all logical operators.
I think you have basic JavaScript methodology question here.
Now, JavaScript is a loosely typed language. As such, the way and manner in which it treats logical operations differs from that of other standard languages like Java and C++. JavaScript uses a concept known as "type coercion" to determine the value of a logical operation and always returns the value of the first true type. For instance, take a look at the code below:
var x = mystuff || document;
// after execution of the line above, x = document
This is because mystuff is an a priori undefined entity which will always evaluate to false when tested and as such, JavaScript skips this and tests the next entity for a true value. Since the document object is known to JavaScript, it returns a true value and JavaScript returns this object.
If you wanted a boolean value returned to you, you would have to pass your logical condition statement to a function like so:
var condition1 = mystuff || document;
function returnBool(cond){
if(typeof(cond) != 'boolean'){ //the condition type will return 'object' in this case
return new Boolean(cond).valueOf();
}else{ return; }
}
// Then we test...
var condition2 = returnBool(condition1);
window.console.log(typeof(condition2)); // outputs 'boolean'
We can refer to the spec(11.11) of JS here of:
Semantics
The production LogicalANDExpression :LogicalANDExpression &&BitwiseORExpression is evaluated as follows:
Evaluate LogicalANDExpression.
2.Call GetValue(Result(1)).
3.Call ToBoolean(Result(2)).
4.If Result(3) is false, return Result(2).
5.Evaluate BitwiseORExpression.
6.Call GetValue(Result(5)).
7.Return Result(6).
see here for the spec
First, it has to be true to return, so if you are testing for truthfulness then it makes no difference
Second, it lets you do assignments along the lines of:
function bar(foo) {
foo = foo || "default value";
Compare:
var prop;
if (obj.value) {prop=obj.value;}
else prop=0;
with:
var prop=obj.value||0;
Returning a truthy expression - rather than just true or false - usually makes your code shorter and still readable. This is very common for ||, not so much for &&.

what is the issue in this javascript short circuit assignment

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

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.

Seemingly redundant ternary operators in javascript

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.

Categories