Why doesn't one approach to setting prop work (jQuery)? - javascript

Commment.isDefault evaluates to 'true' or 'false'.
The goal is to dynamically update a checkbox.
This works:
if (Comment.isDefault == 'false'){
// console.log("Checked.");
$('#chkDefault'+ i).prop('checked', true);
}
else {
// console.log("NOT Checked.");
$('#chkDefault'+ i).prop('checked', false);
}
This does not work:
$('#chkDefault'+ i).prop('checked', Comment.isDefault);
The non-working case just makes every checkbox TRUE.
I'd like the more elegant solution plus understanding why just using the variable to set the property doesn't work.
Thoughts? Much appreciated!

If you try this:
console.log(typeof Comment.isDefault); // string
console.log(typeof "false"); // string
console.log(typeof false); // bool
Also not empty string are alway true ( the ! return the inverse boolean, so !! return the boolean equivalent)
console.log(!!"true") // true
console.log(!!"false") // true
console.log(!!"") // false
console.log(!!true) // true
console.log(!!false) // false
You have to update (best choice):
Comment.isDefault = true; // or = false; instead of 'true'
Or you can also test the string value (if you can't easily update the Comment.isDefault value):
$('#chkDefault'+ i).prop('checked', Comment.isDefault == 'true');

The issue is that false != 'false'.
Comment.isDefault contains a string, not a boolean. Non-empty strings are always truthy. I'd suggest converting your boolean string into a proper boolean value then use it as such.
Comment.isDefault = (Comment.isDefault === 'true');

Because your Comment.isDefault is having string value of 'true' or
'false'
Setting non-empty string value in place of boolean, evaluates as true. Thus, all checkboxes are set to true.
Possible elegant looking solution
$('#chkDefault'+ i).prop('checked', JSON.parse(Comment.isDefault));
Possible faster solution (I will pick this over elegant one, thanks to #arthur)
$('#chkDefault'+ i).prop('checked', Comment.isDefault == "true");
JsFilddle Link

Related

Checking whether variable is empty in JavaScript?

There is two kind of JavaScript code for investigating empty/full variable:
if(variable == ''){}
if(!variable){}
I tested both of them, and I achieved identical result. Now I want to know, (first) are they equivalent? And (second) which one is more standard for checking empty/full variable?
var variable1 = 'string';
var variable2 = 12;
var variable3 = true;
if(variable1 == ''){alert('empty-one');}
if(variable2 == ''){alert('empty-one');}
if(variable3 == ''){alert('empty-one');}
if(!variable1){alert('empty-two');}
if(!variable2){alert('empty-two');}
if(!variable3){alert('empty-two');}
As you see, there is no alert.
First is not standard, it only works for defined empty string.
Other will work if value is not truthy ( means something meaningful)
e.g var a;
a == '' will give false result
! a will produce true
e.g. var a = null;
a == '', // false
! a // true
var a = false;
a == '' // fase
! a // true
var a = NaN
a == '' // false
! NaN // true
true == 'true' // false, Boolean true is first converted to number and then compared
0 == '' // true, string is first converted to integer and then compared
== uses The Abstract Equality Comparison Algorithm to compare two operands
For more detail visit http://www.ecma-international.org/ecma-262/5.1/#sec-11.9.3
In javascript null,'',0,NaN,undefined consider falsey in javascript.
In one sense you can check empty both way
But your first code are checking is it ''
and your 2nd condition is checking is your value are one of them (null,'',0,NaN,undefined)
In my view your 2nd condition is better then first as i don't have to check null,'',0,NaN,undefined seperately
No they are not equivalent. In case first it checks whether the value of variable is equal to the empty string('') or not. So case first will be true iff variable's value is ''. But second case will be true for all the values which are falsey i.e. false, 0, '', null, undefined.

Comparing NaN values for equality in Javascript

I need to compare two numeric values for equality in Javascript. The values may be NaN as well.
I've come up with this code:
if (val1 == val2 || isNaN(val1) && isNaN(val2)) ...
which is working fine, but it looks bloated to me. I would like to make it more concise. Any ideas?
if(val1 == val2 || (isNaN(val1) && isNaN(val2)))
Nothing to improve. Just add the parentheses to make it clear to everyone.
Avoid isNaN. Its behaviour is misleading:
isNaN(undefined) // true
_.isNaN (from Underscore.js) is an elegant function which behaves as expected:
// Is the given value `NaN`?
//
// `NaN` is the only value for which `===` is not reflexive.
_.isNaN = function(obj) {
return obj !== obj;
};
_.isNaN(undefined) // false
_.isNaN(0/0) // true
Try using Object.is(), it determines whether two values are the same value. Two values are the same if one of the following holds:
both undefined
both null
both true or both false
both strings of the same length with the same characters in the same order
both the same object
both numbers and
both +0
both -0
both NaN
or both non-zero and both not NaN and both have the same value
e.g. Object.is(NaN, NaN) => true
Refer to https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is
if ( val1 === val2 )
If either one or both are NaN it will evaluate to false.
Also, NaN !== NaN
As long as you know these two variables are numeric, you can try:
if (val1 + '' == val2 + '')
It turns the two values into strings. A funny answer, but it should work. :)
NaN is never equal to itself no matter the comparison method, so the only more concise solution for your problem that I can think of would be to create a function call with a descriptive name for doing this rather special comparison and use that comparison function in your code instead.
That would also have the advantage of localizing changes to the algorithm the day you decide that undefined should be equal to undefined too.
And what's about the function Number.isNaN() ? I believe this must be used whenever is possible.
> NaN === NaN
false
> Number.isNaN
ƒ isNaN() { [native code] }
> Number.isNaN() === Number.isNaN()
true
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/isNaN
For Numeric cases the solution is fine but to extend it to work for other data-types as well my suggestion would be as follows:
if(val1 === val2 || (val1 !== val1 && val2 !== val2))
Reason being global isNaN is erroneous. It will give you wrong results in scenarios like
isNaN(undefined); // true
isNaN({}); // true
isNaN("lorem ipsum"); // true
I have posted a comprehensive answer here which covers the NaN comparison for equality as well.
How to test if a JavaScript variable is NaN
Why not an if statement like this?
if (isNaN(x) == true){
alert("This is not a number.");
}
Equality comparison with NaN always results in False.
We can go for the javascript function isNaN() for checking equality with NaN.
Example:
1. isNaN(123) //false
2. var array = [3, NaN];
for(var i = 0 ; i< array.length; i++){
if(isNaN(array[i])){
console.log("True ---- Values of " + i);
} else {
console.log("false ---- Values of " + i);
}
}
Results:
false ---- Values of 0
True ---- Values of 1
Found another way using Array.prototype.includes MDN link. Apparently, [NaN].includes(NaN) returns true for NaN.
function IsActuallyNaN(obj) {
return [obj].includes(NaN);
}
Or we can go with davidchambers' solution which is much simpler.
function IsActuallyNaN2(obj) {
return obj !== obj;
}

JS if/else trouble

I have a simple code:
<script type="text/javascript">
jQuery(document).ready(function() {
jQuery("#continue").click(function() {
var value = jQuery('#continue').attr('value')
alert (value);
if (value='next'){
jQuery('#msg_title').html('blablabla');
jQuery('#msg').html('blablabla'');
jQuery('#continue').attr('value','removeConfig');
value = jQuery('#continue').attr('value');
}
else if (value='removeConfig') {
jQuery('#msg_title').html('It Works!');
}
else {
alert ('Something wrong')
}
return false;
});
});
</script>
It works well in firs if phase, changes button's value (as I see from alert), but doesn't make else if and else statements.
Your comparison operator is wrong: if (value='next') should be if (value == 'next'){ or if (value === 'next'){.
Note the extra = signs.
You need ==
(value='next'){
should be:
(value == 'next'){
You are testing if ('next') { which is always true. Only string the evaluates to false is empty string, ""
Use ==, not =. A single = is an assignment operator, which means it's assigning "next" to value, then testing if value is false, not if value equals next
You need double equals signs as singles will return true in this case:
if (value =="next")
Single = is an assignment operator and double == is a comparison operator. Since you were using an assignment operator and setting the variable to a non falsy value the first if statement resolved to true.

Javascript if condition on boolean

Can you explain why the if condition doesn't work without the eval function:
var myBoolean= document.getElementById("someBoolean").value; //This is a 'false'
if(myBoolean)
{
alert(Your boolean is True); //This condition always getting executed even though myBoolean is false;
}
if(eval(myBoolean))
{
alert("You will never see this alert bcoz boolean is false");
}
In Javascript the following values are treated as false for conditionals:
false
null
undefined
The empty string ''
The number 0
The number NaN
Everything else is treated as true.
'false' is none of the above, so it's true.
The string 'false' evaluates to the boolean true
This is because it's not actually a boolean, it's a the string 'false'. When you convert a string to a boolean, '' is false and anything else is true.
You check if it's equal to the string 'false' (or 'true') or not.
var myBoolean = 'false'; // (string)
myBoolean = myBoolean !== 'false'; //false (boolean)
'false' == true, crazily enough because of JavaScript's implicit type coercion. Check out these other examples from Crockford's The Elements of JavaScript Style.
'' == '0' // false
0 == '' // true
0 == '0' // true
false == 'false' // false
false == '0' // true
false == undefined // false
false == null // false
null == undefined
// true
' \t\r\n ' == 0 // true
You could solve this particular problem by changing your code to something like
var myBoolean = document.getElementById("someBoolean").value === "true"
Also, it is almost always better to use !! and === rather than ! and ==
document.getElementById("someBoolean") does not return a boolean true/false it returns an element or undefined / null
you could reverse your logic and get the expected result:
if(!myBoolean)
{
alert('This element does not exist');
}
if(!eval(myBoolean))
{
alert("Do not know why you would ever want to do this");
// you could do typeof()
}
Try:
var myBoolean= document.getElementById("someBoolean").value; //This is a 'false'
if(myBoolean != "false")
{
alert(Your boolean is True); //This condition always getting executed even though myBoolean is false;
}
Like others have said, a string isn't a boolean value, so using it as though it was will give you a logical error.
A string IS a boolean truth value according to ECMA
var a = ""<br/>
a&&false //-> false<br/>
a||false //-> "" (truthy)<br/>

Convert string to Boolean in javascript [duplicate]

This question already has answers here:
How can I convert a string to boolean in JavaScript?
(102 answers)
Closed 5 years ago.
How to convert a string to Boolean ?
I tried using the constructor Boolean("false"), but it's always true.
I would use a simple string comparison here, as far as I know there is no built in function for what you want to do (unless you want to resort to eval... which you don't).
var myBool = myString == "true";
I would like to answer this to improve upon the accepted answer.
To improve performance, and in real world cases where form inputs might be passing values like 'true', or 'false', this method will produce the best results.
function stringToBool(val) {
return (val + '').toLowerCase() === 'true';
}
JSPerf
you can also use JSON.parse() function
JSON.parse("true") returns true (Boolean)
JSON.parse("false") return false (Boolean)
Actually you don't get the meaning of Boolean method.It always return true if the variable is not null or empty.
var variable = some value;
Boolean(variable);
If my variable have some value then it will
return true
else
return false
You can't use Boolean as you think.
trick string to boolean conversion in javascript. e.g.
var bool= "true";
console.log(bool==true) //false
var bool_con = JSON.parse(bool);
console.log(bool_con==true) //true
I am still amazed how people vote blindly for solutions that won't work, like:
var myBool = myString == "true";
The above is so BUGGY!!!
Not convinced? Just try myString = true (I mean the boolean true). What is the evaluation now? Opps: false!
Alternative
var myString=X; // X={true|false|"true"|"false"|"whatever"}
myString=String(myString)=='true';
console.log(myString); // plug any value into X and check me!
will always evaluate right!
Depends on what you see as false in a string.
Empty string, the word false, 0, should all those be false or is only empty false or only the word false.
You probably need to buid your own method to test the string and return true or false to be 100 % sure that it does what you need.
I believe the following code will do the work.
function isBoolean(foo) {
if((foo + "") == 'true' || (foo + "") == 'false') {
foo = (foo + "") == 'true';
} else {
console.log("The variable does not have a boolean value.");
return;
}
return foo;
}
Explaining the code:
foo + ""
converts the variable 'foo' to a string so if it is already boolean the function will not return an invalid result.
(foo + "") == 'true'
This comparison will return true only if 'foo' is equal to 'true' or true (string or boolean). Note that it is case-sensitive so 'True' or any other variation will result in false.
(foo + "") == 'true' || (foo + "") == 'false'
Similarly, the sentence above will result in true only if the variable 'foo' is equal to 'true', true, 'false' or false. So any other value like 'test' will return false and then it will not run the code inside the 'if' statement. This makes sure that only boolean values (string or not) will be considered.
In the 3rd line, the value of 'foo' is finally "converted" to boolean.
These lines give the following output:
Boolean(1).toString(); // true
Boolean(0).toString(); // false
Unfortunately, I didn't find function something like Boolean.ParseBool('true') which returns true as Boolean type like in C#.
So workaround is
var setActive = 'true';
setActive = setActive == "true";
if(setActive)
// statements
else
// statements.
javascript:var string="false";alert(Boolean(string)?'FAIL':'WIN')
will not work because any non-empty string is true
javascript:var string="false";alert(string!=false.toString()?'FAIL':'WIN')
works because compared with string represenation
See this question for reference:
How can I convert a string to boolean in JavaScript?
There are a few ways:
// Watch case sensitivity!
var boolVal = (string == "true");
or
var boolVal = Boolean("false");
or
String.prototype.bool = function() {
return (/^true$/i).test(this);
};
alert("true".bool());
You can try this:
var myBoolean = Boolean.parse(boolString);

Categories

Resources