0

Curious to know what and why is correct?

I'm asking because I'm never sure what to use when.

This:

function foo(){
    $('.bar')
        .click(function(){
            var baq = 'baz';
        })
}

Or this

function foo(){
    var baq;
    $('.bar')
        .click(function(){
            baq = 'baz';
        })
}

And also this:

function foo(){
    $('.bar')
        .click(function(){
            let baq = 'baz';
        })
}

Or this

function foo(){
    let baq;
    $('.bar')
        .click(function(){
            baq = 'baz';
        })
}
Bob van Luijt
  • 7,153
  • 12
  • 58
  • 101

2 Answers2

1

Answering the first two pieces of code.

Let's say you click on an item with classname bar, and when you do this, you want to set baq to the value of baz, and that's it.You aren't really concerned with the variable baq after the click occurs. Here the variable is local in its scope.

function foo(){
$('.bar')
    .click(function(){
        var baq = 'baz';
    })}

Now, maybe you are concerned about variable baq. Let's say you're building a pizza?Baq is first a string variable " ".

In the first function, you add cheese,some people may not.So i say baq="Cheese". In the next selection, let's say there is a class "vegetables".When someone clicks on a vegetable, I add a veggie, baq=baq+"mushrooms". Next, there is a class "meat".Similarly, so on.

In the essence, when I want to reuse baq, i use the following, where the variable is global in it's scope.Click on the cheese and mushrooms in the JSFIDDLE

function foo(){
var baq;
$('.bar')
    .click(function(){
        baq = 'baz';
    })}

For information about usage of let,check this link

Community
  • 1
  • 1
Satej S
  • 2,113
  • 1
  • 16
  • 22
0

it depends!!

scenario 1: change variables depending upon events

    function foo(){
    var baq;// to avoid scope conflicts
        baq = 0;
    $('.bar')
        .click(function(){
            baq++;//increment baq with click event
        })
}

scenario 2: dealing with context

    function foo(){
    var baq;// to avoid scope conflicts
        baq = $(this);
    $('.bar')
        .click(function(){
            baq = $(this);
        })
}

i can't imagine all cases.but there is a good video on youtube about this. video

varun teja
  • 244
  • 3
  • 10