Optimized True/False Assignments in JavaScript

Ever write some javascript and find typing =true or =false just way too time consuming? Why not rely on some boolean assignment operators to do the trick? To make something true, use |=1. To make something false, use &=0.

How and why does this work? Let's take a look at each one seperately. In the true example, we have |=1. What this basically means is take the value on the left of operator and perform a boolean OR (the pipe | ) on it with the number 1. When ORing, if both values are 0 then the result is 0. If either are 1 then the result is 1. By ORing our variable with 1, we guarantee that the result will always be true.

We use the JavaScript shorthand for performing an arithmetic task with an assignment. If you needed to add two numbers together you could use myvar=20; myvar+=20; // myvar = 40.

Okay, on to our second example: &=0. This time we perform a boolean AND (the ampersand &) with the number 0. When ANDing, both values have to be 1 in order for the result to be 1. Otherwise, the result is 0. Therefore, we AND it with 0 to ensure that the result will always be false.

Just like that, you've saved 2 to 3 bytes per assignment! (cue parade...)

Published March 11, 2005 · Updated September 17, 2005
Categorized as JavaScript
Short URL: https://snook.ca/s/347

Conversation

3 Comments · RSS feed
Agustin said on March 11, 2005

Ever write some javascript and find typing =true or =false just way too time consuming?

Ha ha ha! Nice!

tim said on June 22, 2005

why not just say =1and =0 ???

Jonathan Snook said on June 22, 2005

tim: but what's the fun in that? :)

Sorry, comments are closed for this post. If you have any further questions or comments, feel free to send them to me directly.