Logical XOR in JavaScript

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
VN:F [1.9.3_1094]
Rating: 5.0/5 (1 vote cast)
Logical XOR in JavaScript, 5.0 out of 5 based on 1 rating
This entry was posted in JavaScript and tagged . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">

Additional comments powered by BackType