Yogesh
Yogesh

Reputation: 150

JavaScript code syntax for bool value assignment to html object

below is code , both code works but i am trying to findout which is more perfect for browsers

Which code is right?

   <script>

document.getElementById("firstbtn").disabled=true;

</script>

or

<script>

document.getElementById("firstbtn").disabled='true';

</script>

also when we compare in

if(document.getElementById("firstbtn").disabled ==true)

or

if(document.getElementById("firstbtn").disabled =='true')

Upvotes: 2

Views: 83

Answers (2)

James Donnelly
James Donnelly

Reputation: 128791

It's important to understand which values evaluate to false in JavaScript. Falsy values are: undefined, null, NaN, 0 -0, "", and false. This means that everything else evaluates to true:

document.getElementById("firstbtn").disabled=true /* True */
document.getElementById("firstbtn").disabled="true" /* True */
document.getElementById("firstbtn").disabled="false" /* True */
document.getElementById("firstbtn").disabled="banana" /* True */
document.getElementById("firstbtn").disabled=1 /* True */
document.getElementById("firstbtn").disabled=4723598495 /* True */
document.getElementById("firstbtn").disabled=false /* False */
document.getElementById("firstbtn").disabled="" /* False */
document.getElementById("firstbtn").disabled=0 /* False */
document.getElementById("firstbtn").disabled=NaN /* False */

Because of this and as you can see above, "false" is evaluated to true as it is a string with length greater than 0.

On the subject of which is right, the answer would be that both are. Both get the job done. You may as well just use disabled=true, however, to avoid potential confusion at a later date.

Upvotes: 1

Quentin
Quentin

Reputation: 943564

Use a boolean. The string only works because when it is cast to a boolean it is evaluated as true. If you were to assign "false" then that string would also be evaluated as true.

Upvotes: 3

Related Questions