Zach’s ugly mug (his face) Zach Leatherman

Logical XOR in JavaScript

March 23, 2007

Of course there wouldn’t be an XOR function in JavaScript when I needed one. So I googled around and found an implementation at How To Create. But it only took two arguments. So I rolled my own supporting a variable number of arguments. In my personal stuff, I’ve put it into a Math library under the YAHOO namespace, and you can decide if you want to do that on your own.

function xor() {
  var b = false;
  for( var j = 0; j < arguments.length; j++ ) {
    if( arguments[ j ] && !b ) b = true;
    else if( arguments[ j ] && b ) return false;
  }

  return b;
};

Usage:

xor( false, true ); // true
xor( true, true ); // false
xor( false, false, true, true, true, false, true, false ); // false
xor( false, false, false, true, false, false, false, false ); // true

< Newer
Google Using YUI Grids CSS
Older >
Conservative Design Example: Hierarchical Options

Zach Leatherman IndieWeb Avatar for https://zachleat.com/is a builder for the web at IndieWeb Avatar for https://cloudcannon.com/CloudCannon. He is the creator and maintainer of IndieWeb Avatar for https://www.11ty.devEleventy (11ty), an award-winning open source site generator. At one point he became entirely too fixated on web fonts. He has given 79 talks in nine different countries at events like Beyond Tellerrand, Smashing Conference, Jamstack Conf, CSSConf, and The White House. Formerly part of Netlify, Filament Group, NEJS CONF, and NebraskaJS. Learn more about Zach »

2 Comments
  1. Nagy Gergely Disqus

    06 Nov 2017
    Come on, this is clearly incorrect. It is obvious from the code, no XOR implementation can return early (inside the loop), as the result of the XOR _always_ depends on all the input bits. This is the reason why it is used in checksums.xor(1,0,1,1) should yield true, your implementation yields false.Please remove the page or fix it.
    1. zachleat Disqus

      13 Nov 2017
Shamelessly plug your related post

These are webmentions via the IndieWeb and webmention.io.

Sharing on social media?

This is what will show up when you share this post on Social Media:

How did you do this? I automated my Open Graph images. (Peer behind the curtain at the test page)