1

While looking through an old codebase of ours, I came upon this little snippet:

var getElementByXpath = function (path) {
    return document.evaluate(path, document, null, 9, null).singleNodeValue;
};

Why did they declare a variable and assign an anonymous function to it, rather than simply create a named function? How is that any different from the (much more normal and common) following?

function getElementByXpath(path) {
    return document.evaluate(path, document, null, 9, null).singleNodeValue;
};
Soviero
  • 1,774
  • 2
  • 13
  • 23
  • 2
    The main difference I know of is that if you declare the function as a variable, the function can only be called after the declaration. Simply using function name() is better because a: it takes less to type and b: it can be called from anywhere not just after. – Tai Kwangi Chicken Dec 11 '14 at 18:09
  • 1
    @GwiddleWorker There's no "better" case here, the usage is just different. – Teemu Dec 11 '14 at 18:15
  • 1
    @Teemu: Though in the many cases where both would work, function declarations [only have advantages](http://blog.niftysnippets.org/2010/03/anonymouses-anonymous.html) over function expression assignments. – Bergi Dec 11 '14 at 18:32

0 Answers0