1

What difference does it make to do the following:

function (callback) {
    var callback  = callback || false;
    combineCallback = function () {
        callback.apply(window);
        ....
    }
    getJSON(combineCallback);
}

Or with this:

function (callback) {
    var combineCallback = function () {
        callback.apply(window);
        ....
    }
    getJSON(combineCallback);
}

Does it make any difference to write write var callback = callback || false;?

dda
  • 6,030
  • 2
  • 25
  • 34
Basit
  • 16,316
  • 31
  • 93
  • 154
  • if the function is called more than once.. will it be overright with previous callback if i don't define var? – Basit May 31 '13 at 06:22
  • `false.apply()` and `undefined.apply()` throw a similar error, so in that regard there is no difference. – JJJ May 31 '13 at 06:24

1 Answers1

1

var will not "shadow" a local variable in the same scope. Likewise, var will not "shadow" a parameter (which is a local variable/binding itself). Simply, each time the function is invoked, callback represents a different local variable which initially contains the first argument passed; and there is only one local variable called callback.

Because var doesn't "create" a new variable (search for "hoisting"),

function (callback) {
    var callback  = callback || false;

and

function (callback) {
    callback  = callback || false;

are equivalent - no difference. (Although I find the latter more clear.)

However, removing the callback = callback || false changes the semantics. In particular, callback may end up with false-y values like 0 without that line. Whether or not this is needed/useful here is a different issue as (false).apply(..) will still result in an error.

Here is a simple TTL for x || y:

x        y    x || y
-------  ---  ------
TRUTH-y  ANY  x
FALSE-y  ANY  y
user2246674
  • 7,621
  • 25
  • 28
  • I think that the OP's question is if including `var callback = callback || false;` in the code will make a difference or not. – Harsha Venkataramu May 31 '13 at 06:23
  • you edited the answer milliseconds before I posted the comment.Sorry! – Harsha Venkataramu May 31 '13 at 06:24
  • f the function is called more than once.. will it be overright with previous callback if i don't define var? – – Basit May 31 '13 at 06:25
  • @Juhana i have head problem with var before, thats why i was asking.. this was the error before http://stackoverflow.com/questions/16608355/getting-the-rangeerror-maximum-call-stack-size-exceeded-error – Basit May 31 '13 at 06:29
  • 1
    @Basit The problem with the code in the linked question is it *doesn't* use `var`. It would awful if parameters "leaked" scope or were "promoted" to global variables! That would lead to so many bugs that could not help but be avoided! Anyway, the `var` in this case is completely irrelevant to how the code will run. – user2246674 May 31 '13 at 06:37