Note that there are some explanatory texts on larger screens.

plurals
  1. POreturn opposite Boolean value in one line
    primarykey
    data
    text
    <p>Common Javascript knowledge (or any programming language really) tells us that using <code>!variable</code> will equal the opposite value when it's Boolean (or converted to Boolean in a conditional, etc).</p> <h2>I have this Javascript:</h2> <pre><code>$(document).ready(function () { var addEvent = function (element, myEvent, fnc) { return ((element.attachEvent) ? element.attachEvent('on' + myEvent, fnc) : element.addEventListener(myEvent, fnc, false)); }; var openBar = false; addEvent(document.getElementById('toggle'), 'click', function (event) { var toggler = event.currentTarget, barWrap = document.getElementById('left-wrap'), newSize = (!openBar) ? 20 : 0; $(barWrap).animate({ width: (newSize / 100 * window.innerWidth) }, { queue: false, duration: 300, step: function (now) { toggler.style.right = now + 'px'; //barWrap.outerWidth = now; document.body.style.marginRight = now + 'px'; }, complete: function () { newSize = (newSize === 20) ? '20%' : '0%'; document.body.style.marginRight = newSize; toggler.style.right = newSize; barWrap.style.width = newSize; } }); return !openBar; }); }); </code></pre> <p>...that I threw into <a href="http://jsfiddle.net/3R5qe/" rel="nofollow">this JSFiddle</a>...which will show it open the toggle bar but not close it...with a lot of fluffy HTML and CSS too prettify it for y'all.</p> <p>Now, why on earth does the 3rd to last line NOT return the opposite value as it should? I have successfully used the following:</p> <pre><code>return openBar = !openBar; </code></pre> <p>but for some reason browsers and JSfiddle and JShint like to get mad when I do because they expect a conditional or value instead of assignment. But they don't fail to load. I also know I can use:</p> <pre><code>openBar = !openBar; return openBar; </code></pre> <p>or even</p> <pre><code>openBar = !openBar; return; </code></pre> <p>but I like to minimize everywhere I can and really just want to understand why this fundamentally is failing to work for me so I can correct it in the future.</p> <p>Is this in anyway incompatible with another browser (using Chrome 30 and Firefox 25) or possibly going to error out somewhere I'm not anticipating? </p> <p>Or is it more of an inconvenience/warning that I can ignore (like those things telling me to use === instead of == when comparing 0 when I know the result can only be a number)?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload