2

I was cleaning up some code on my homepage and found one of my jquery functions I had written like so:

$(function(){
        var hash = window.location.hash;
        hash && $('[id^=search] a[href="' + hash + '"]').tab('show');

        $('[id^=search] a').click(function (e) {
        $(this).tab('show');
        var scrollmem = $('body').scrollTop();
        window.location.hash = this.hash;
        $('html,body').scrollTop(scrollmem);
  });
});

This particular piece changes tabs on the homepage when an external link contains a hash that matches with any hashes in my navigation. I hadn't worked with this snippet in a while (this was one of the first things I ever did for my website.) and I cannot for the life of me work out in my brain what hash && $('[id^=search] a[href="' + hash + '"]') translates to. If I were to think of it as plain english, what would it be?

David-SkyMesh
  • 4,761
  • 1
  • 27
  • 38
Habitat
  • 709
  • 10
  • 21

3 Answers3

3

It is like if statement:

if (hash) {
  $('[id^=search] a[href="' + hash + '"]').tab('show');
}

This is equivalent to:

hash && $('[id^=search] a[href="' + hash + '"]').tab('show');

If the condition evaluates to true then only the next statement after && is executed.

Tushar
  • 78,625
  • 15
  • 134
  • 154
1

The output of hash && $('[id^=search] a[href="' + hash + '"]').tab('show') will be the same if you put the entire thing inside an if.

Swaraj Giri
  • 3,801
  • 2
  • 20
  • 36
1

The logical operator && will evaluate the second operand only if the first one is truthy so it is the same as

if(hash)
    $('[id^=search] a[href="' + hash + '"]').tab('show');

so the $('[id^=search] a[href="' + hash + '"]').tab('show'); will get executed only if there is a hash value present in the location.

Arun P Johny
  • 365,836
  • 60
  • 503
  • 504