Search code examples
javascriptsyntaxshorthandshorthand-if

javascript shorthand syntax


I was wondering how this could be written in shorthand that the statement would execute

This one isn't working, but I see this kind of syntax lots of times in plugins - variables mixed with statements etc..

Can someone give an explanation regarding the proper use of this shorthand syntax? I want to "execute" NOT "evaluate" the second statement if the first evaluates to true!

var succes = !data.user||(window.location = "users/profile");

I knew the first example was way to simple, This one is better, it also uses comma,s to string statements after eachother, I like to know how to learn this syntax.

},
        hide: function (a,
        b) {
            if (f && !(500 > (new Date).getTime() - f.getTime())) {
                if (!a || "number" == typeof a) a = k();
                b || (b = $(".profile-popup"));
                j(a) && (b.fadeOut("fast"), m(!1, a));
                e && (clearInterval(e), e = null)
            }
        }
    }
}();

EDIT I changed my first example to use the && in my code and it worked, so, that's that - for anyone else reading -, and you should use absolute url's if working with window.location

I also found another detailed explanation over here.

thanks, Richard


Solution

  • The general pattern of !obj || obj = "something" is simply shorthand for:

    if (obj === undefined) {
        obj = "something";
    }
    

    That's because !obj evaluates to false if it's undefined (the pattern also seems to assume that obj will not be defined as true).

    Likewise, the pattern f(a) && (g(b), h(c)) is shorthand for:

    if (f(a) == true) {
        g(b);
        h(c);
    }
    

    For the referenced piece of code:

    var succes = !data.user||(window.location = "users/profile");
    

    What this implicitly says is:

    1. If data.user is undefined, then set success to true.
    2. Otherwise (if data.user is assigned), then redirect to users/profile.

    The exact meaning is anyone's guess without knowing the context, but it appears to mean "redirect the profile screen, if user data is available, otherwise ..."