title: Javascript - Converting colors (numbers -> strings) vice versa
body: <pre><code>utils.parseColor = function (color, toNumber) {
    if (toNumber === true) {
      if (typeof color === 'number') {
        return (color | 0); //chop off decimal
      }
      if (typeof color === 'string' &amp;&amp; color[0] === '#') {
        color = color.slice(1);
      }
      return window.parseInt(color, 16);
    } else {
      if (typeof color === 'number') {
        //make sure our hexadecimal number is padded out
        color = '#' + ('00000' + (color | 0).toString(16)).substr(-6);
      }
  
      return color;
    }
  };
  </code></pre>
  <p>I encountered this piece of code. It is a utility function in JavaScript that will convert colors back and forth between numbers and strings. There are 2 parts that I am not so sure of:</p>
  <ol>
  <li><p>What does <code>return (color|0);</code> mean? What is <code>|</code>? in JavaScript?</p>
  </li>
  <li><p>In the line <code>color = '#' + ('00000' + (color | 0).toString(16)).substr(-6);</code>, why do I need to make sure the hexadecimal number is padded out? What are we trying to achieve here?</p>
  </li>
  </ol>
  <hr />
  <p>Calling the function with a hexadecimal number like <code>utils.parseColor(0xFFFF00)</code>, returns the string
  value: <code>&quot;#ffff00&quot;</code>. Passing a CSS-style hexadecimal string returns the same string unmodified. The
  function also accepts a second, optional, parameter <code>toNumber</code>, which if set to <code>true</code>, returns a numeric
  color value. For example, calling <code>utils.parseColor(&quot;#FFFF00&quot;, true)</code> or
  <code>utils.parseColor(0xFFFF00, true)</code>, both return the number <code>16776960</code>.</p>