rohn
rohn

Reputation: 75

The ! operator in Javascript turns true to false an viceversa right?

Learning Javascript, early beginner. I'm confused about the use of the ! operator in this bit of script:

  var switchDirection = false;

    function doAnimation() {
        var divAdvert = document.getElementById("divAdvert");
        var currentLeft = divAdvert.offsetLeft;
        var newLocation;

        if (!switchDirection) {
            newLocation = currentLeft + 2;

            if (currentLeft >= 400) {
                switchDirection = true;
            }
        } 

It's not complete but it's a simple bidirectional sliding text. The logic as I understand it is: if switchDirection is false, add 2 pixels to currentLeft and store it in newLocation.

The thing is if switchDirection was initialized as false, then why (!switchDirection) still returns false? I thought the ! operator turned it to true.

(!switchDirection) is the same as (switchDirection == false). The second statement I completely understand, but the first doesn't get into my thick skull.

Upvotes: 2

Views: 852

Answers (2)

gnomeria
gnomeria

Reputation: 190

As others have answered how the negations work, if you want to implement other method in order to clear the confusion, there's also an enum in javascript:

var Direction = {
    LEFT: 1,
    RIGHT: 2
};

var switchDirection = Direction.LEFT;

    function doAnimation() {
        var divAdvert = document.getElementById("divAdvert");
        var currentLeft = divAdvert.offsetLeft;
        var newLocation;

        if (switchDirection == LEFT) {
            newLocation = currentLeft + 2;

            if (currentLeft >= 400) {
                switchDirection = Direction.RIGHT;
            }
        } 

Or even better use an Object.freeze() in the enum:

var Direction = Object.freeze({LEFT: 1, RIGHT:2})

Upvotes: 2

Adarsh Konchady
Adarsh Konchady

Reputation: 2737

if always executes the block if the condition passed to it(in this case !switchDirection) is truthy.

!switchDirection evaluates to !false, i.e. true.

Hence !switchDirection is not same as switchDirection == false.

Another point you seem to be confused at is how ! operator works. The ! operator doesn't actually modify the original value. It just returns the negated value. Hence in this case, !switchDirection returns false but the value of switchDirection remains true in if condition. switchDirection is explicitly set to true later in your code.

Upvotes: 2

Related Questions