How do I compare string and boolean in Javascript? - javascript

I got the Json "false" from server. I respond as bool but it's Json so it's in browser type is String instead of bool.
So if I run (!data) whenever I want to check "false" == false then they not worked.
So how can I parse bool from String in JavaScript then?
"true" == true and "false" == false. Then the code (!data) can check what it is [true and false]

If one of the operands is a boolean, convert the boolean operand to 1 if it is true and +0 if it is false.
When comparing a number to a string, try to convert the string to a numeric value.
from MDN Equality Operators page
Examples:
true == "true"; // 1 == NaN → false
true == "1"; // 1 == 1 → true
false == "false"; // 0 == NaN → false
false == ""; // 0 == 0 → true
false == "0"; // 0 == 0 → true

I would just explicitly check for the string "true".
let data = value === "true";
Otherwise you could use JSON.parse() to convert it to a native JavaScript value, but it's a lot of overhead if you know it's only the strings "true" or "false" you will receive.

var data = true;
data === "true" //false
String(data) === "true" //true
This works fine.

Try expression data == "true"
Tests:
data = "false" -- value will be false
date = "true" -- value will be true
Also, fix your JSON. JSON can handle booleans just fine.

If its just a json "false"/"true", you can use,
if(! eval(data)){
// Case when false
}
It would be more cleaner, if you restrict the code to accept only JSON data from server, and always jsonParse or eval it to JS object (something like jquery getJSON does. It accepts only JSON responses and parse it to object before passing to callback function).
That way you'll not only get boolean as boolean-from-server, but it will retain all other datatypes as well, and you can then go for routine expressions statements rather than special ones.
Happy Coding.

I think you need to look at how the JSON data is being generated. You can definitely have a normal JS boolean false in JSON.
{ "value1" : false, "value2" : true }

String.prototype.revalue= function(){
if(/^(true|false|null|undefined|NaN)$/i.test(this)) return eval(this);
if(parseFloat(this)+''== this) return parseFloat(this);
return this;
}
From: http://www.webdeveloper.com/forum/showthread.php?t=147389
Actually, you just need the first "if" statement from the function -- tests to find true or false in the code and the evals it, turning it into the boolean value

if(data+''=='true'){
alert('true');
}
Convert boolean to string by appending with blank string. and then compare with Stringobject.

Related

Does isNaN and NaN have a boolean

I can't seem to understand why when I put in the console
isNaN == true results to false while !isNaN == false returns to true.
When
NaN == true
false
NaN == false
false
Sorry I'm kinda new and somewhat confused.
isNaN is a function which determines if the value is NaN. So isNaN will check if the input is a number or not .
For example isNaN(5) == true will return false , because 5 is a number, Simillarly for empty string isNaN('') == true will also return false it is not a number.
But for isNaN('Hello') == true will return true, since 'Hello' is not a number
Now when using negation(!) it will work oppositely
The isNaN() function determines whether a value is NaN or not.
its return true if the given value is NaN; otherwise, false.
see below link for more info

Check if string zero, zero, empty string, null

in PHP:
$var=0;
$var="";
$var="0";
$var=NULL;
to verify if $var is 0 or "0" or "" or NULL
if (!$var) {...}
in jQuery/JavaScript:
$var=0;
$var="";
$var="0";
$var=NULL;
if (!$var) works for every value except for "0"
Is there a general way in JavaScript/jQuery to check all kinds of those empty/null/zero values, exactly like php does?
Is there a general way in JavaScript/jQuery to check all kinds of those empty/null/zero values, exactly like php does?
No. In PHP, the values converted to booleans produces different results than in JavaScript. So you can't do it exactly like PHP does.
Why not be (a bit more) explicitly about it which makes your code easier to understand?
// falsy value (null, undefined, 0, "", false, NaN) OR "0"
if (!val || val === '0') { }
The abstract operation ToBoolean converts its argument to a value of type Boolean according to Table 11:
Undefined false
Null false
Boolean The result equals the input argument (no conversion).
Number The result is false if the argument is +0, -0, or NaN; otherwise the result is true.
String The result is false if the argument is the empty String (its length is zero);
otherwise the result is true.
Object true
0 will return false.
http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf
Number(variable) seems to produce expected output
Number(0) = 0
Number("0") = 0
Number("") = 0
Number(null) = 0
Number(false) = 0
If you feel funky (just in your exact case-sample) you can do this:
(otherwise undefined and NaN will result as false)
+v===0
Example:
var a = [0, "", "0", null];
var b = [1, "a", "1", {}];
a.forEach(function(v){
console.log( +v===0 ); // true, true, true, true
});
b.forEach(function(v){
console.log( +v===0 ); // false, false, false, false
});
First of "0" isn't false, its true. Because '0' is a string. Strings if they exist return true. So
!"" should return false. That said if your data is returning zeros as strings you can use:
parseInt("0", 10);
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt
This will return the integer value or NaN.
!NaN will return true, and if it is an number of say... 0 it will return !0 so you could do this:
function nullOrEmpty(value) {
return (!value && !parseInt(value));
}
You could very well use a double negative.
var test = 0;
console.log(!!test);
var test = "";
console.log(!!test);
var test = "0";
console.log(!!test);
var test = null;
console.log(!!test);
Although "0" is not an empty string so it evaluates to true, the rest return false.
Also, I agree with the comment that dfsq made in that you shouldn't rely on this. You should know and understand what types your variables are holding.

'hello' == (anything that will return true other than 'hello') in JavaScript?

I understand that == in JavaScript is comparison with type coercion. And I know that the following statements are true:
'' == false;
' ' == false;
'0' == false;
'\n' == false;
However, I can't get a comparison with 'hello' on the left side to be true:
'hello' == true; // no this is false
'hello' == false; // no this is false
'hello' == 1; // no this is false
'hello' == 0; // no this is false
Is there anything 'hello' can be compared to which results in true other than 'hello'?
There is this one:
if('hello') {
alert('true')
}
This will be evaluated as true because the string isn't empty or null.
Since you want a compare:
'hello' == String.fromCharCode.apply(String, [104, 101, 108, 108, 111])
Does this count?
["hello"] == "hello" // true
Here's one:
var x = ['H', 'e', 'l', 'l', 'o'];
x.toString = function() {
return this.join("");
}
alert(x == "Hello"); // true
http://jsfiddle.net/jfriend00/KSgwb/
Or another:
var x = {
toString: function() {return "Hello";}
}
alert(x == "Hello"); // true
http://jsfiddle.net/jfriend00/hKx9x/
If you study the coercion rules for ==, you will find that the only thing that will satisfy == with "Hello" is something that already is a string that is "Hello" or something that has a .toString() method that returns "Hello".
That can be done in as many creative ways as you want by joining an array, returning the string directly, processing a bunch of character codes that combine to form that string, etc... But, in the end, .toString() has to return "Hello" in order to satisfy the == test.
If you aren't allowing the thing you're comparing to to have "Hello" in it in any way or be able to produce that string upon demand, then NO there is nothing else that will satisfy == except something that produces the string "Hello" when asked to coerce to a string.
Here's a layman's description of the type coercion rules for Javascript: http://webreflection.blogspot.com/2010/10/javascript-coercion-demystified.html
In a nutshell, here are the coercion rules when a string is involved:
If both types are a string, then the comparison is true only if the two strings contain exactly the same characters.
If one is a string and the other is a number, then try to convert the string to a number and compare that to the other number. Since Number("Hello") is NaN, this will never work for a number since NaN can't be == to another number.
If one is a string and the other is an object, call the internal method valueOf if it's defined or toString if it's not defined and compare the result of that to your string.
If one is a string and the other is a Boolean, convert both to a number and compare them. Since Number("Hello") is NaN, it will never match a Boolean which will either be 0 or 1 when converted to a Number. For example: true == "1".

javascript : checking boolean values

I have a boolean value set as a hidden variable in the form and I have the below javascript .
$().ready(function() {
var flag = $('#popUpFlag').val();
alert("flag = "+flag);
if(flag){
alert("flag is true");
}else{
alert("flag is false");
}
})
These are the outputs for the alert .
flag =
flag is false
flag = false
flag is false
flag = true
flag is false
My concern is obviously the third output . When the flag is true , why is it printing "flag is false" , instead of "flag is true" . I tested it in IE8 and FF 4
Suggestions are welcome.
No, you don't have a boolean value in the hidden field. The value in the field is always a string.
When you use the string value as if it was a boolean value, you get unexpected results. A condition is false if the value is false, 0, "" or null, but the string "false" is neither, so it's evaluated as true.
If you want a boolean value, you have to parse the string. An easy way is to simply check if the string has a specific value:
var flag = $('#popUpFlag').val() === 'true';
flag is a string, so have this instead:
if (flag === "true") {
//true
}
else if (flag === "false") {
//false
}
Hmm... I suspect that the value you are using is a string, so you're seeing the value correctly in the alert, but not when it tries to look at it like a boolean.
How can I convert a string to boolean in JavaScript?
Just try ocnverting to boolean and see if it still gives you the same issue

JavaScript type casting

Consider empty JavaScript array:
var a = [];
alert(a == false); // shows true
alert(!a); // shows false!
How to explain this?
What are the rules?
From http://forums.whirlpool.net.au/archive/966449:
a == false:
In this case, the type of the left-hand side is object, the type of the right-hand side is boolean. Javascript first converts the boolean to a number, yielding 0. Then it converts the object to a "primitive", yielding the empty string. Next it compares the empty string to 0. The empty string is converted to a number, yielding 0, which is numerically equal to the 0 on the right-hand side, so the result of the entire expression is true.
See §11.9.3 of the ECMAScript spec for all the gory details.
(!a):
In this case Javascript converts the object to the boolean true, then inverts it, resulting in false.
The ! operator checks whether its operand is "falsy".
The following are true:
!false
!0
!null
!NaN
!undefined
!""
The == operator checks for loose equality, which has nothing to do with falsiness.
Specifically, a == b will convert to operands to numbers, then compare the numbers.
Strings containing numbers convert to the numbers that they contain; booleans convert to 0 and 1.
Objects are converted by calling valueOf, if defined.
Thus, all of the following are true:
"1" == 1
"0" == false
"1" == true
"2" != true
"2" != false
({ valueOf:function() { return 2; } }) == 2
({ valueOf:function() { return 1; } }) == true
The == operator when one of the operands if Boolean, type-converts the other to Number.
[] == 0;
Is equivalent to:
0 == 0;
You can see the complete details of The Abstract Equality Comparison Algorithm on the specification.
As you can see, an empty array object, when converted to Number, produces 0:
+[]; // 0
Number(0);
This is really because its toString method produces an empty string, for example:
[].toString(); // ""
+""; // 0
Number(""); // 0
When comparing an object to a primitive value via the == operator, the object coerces into an primitive value itself (number or string). In this case [] coerces into 0, then false coerces into 0:
[] == false
0 == false
0 == 0
which is true.
The ! operator coerces into boolean and then inverts the value. [] into boolean is true (like with any object). Then invert to become false
![]
!true
false
Not sure if this answers the question, but there is a new library for getting around all of Javascript's Typecasting weirdnesses:
Typecast.js
In a sentence, Typecast solves all the simple problems, so you can focus on the big ones. Typecast fixes what's wrong with Javascript by creating a complete platform for strongly-typed variables in Javascript.

Categories