4

I have read a lot of good stuff on truthy and falsy (http://adripofjavascript.com/blog/drips/truthy-and-falsy-values-in-javascript.html), and in particular the differences between '==' and '===' in JavaScript. The best explanations and resources mainly from this Stack Overflow Question:

Which equals operator (== vs ===) should be used in JavaScript comparisons?

I am working on a form and need to store a boolean value into a hidden field with the following jQuery syntax:

$('[name="fieldName"]').val(true);

So I am inserting a boolean value, true or false, into the hidden field. During on screen processing, I grab this field value in a number of if-statements with the following code, and compare it as follows:

$('[name="fieldName"]').val() === "true"

Note how I am using the === operator to compare to the string value "true".

My question; if only Object in JavaScript is of type reference, then boolean must be a value type. I would therefore assume, as value comparisons with the === operator compare not only contents but the type, that the above expression should return false? However in my code it returns true - can anyone explain why this is?

This code previously used == for the comparison, but to avoid falsy risks I am implementing === wherever possible. Could it be something to do with jQuery converting the values for me?

1
  • What is $j in the comparing code? Apr 27, 2016 at 15:47

2 Answers 2

3

Could it be something to do with jQuery converting the values for me?

HTML form elements always store the value as a string, regardless of what the actual content is. In your case it is a boolean, but even if it was say a number type, what you would see is "10.5" not 10.5.

If you'd really like to compare boolean to boolean, what I would recommend is:

Boolean($j('[name="fieldName"]').val()) === true
0
0

Boolean() approach will not work because:

Boolean("true") === true;
Boolean("false") === true;

Seems that only way it is:

$j('[name="fieldName"]').val(true)
$j('[name="fieldName"]').val() === "true"
or
$j('[name="fieldName"]').val(1)
$j('[name="fieldName"]').val() === "1"
etc.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.