0

The javascript code I'm refactoring for work often declares functions as variables and then defines them in a $().readyblock. To be clear, this is what the code is like:

var myFunction;

$().ready(function(){
    myFunction = function() {
    //function body
    }
});

What are the advantages of this practice with respect to a normal function declaration and definition? Are there any or is it just a syntactic difference? I searched through other questions and didn't seem to find anything.

Gixuna
  • 86
  • 8
  • Apart from the declarative difference, the change is in the scope of `myFunction`, although it seems rather pointless, but hard to tell without seeing the larger structure of the code. – Rory McCrossan Feb 26 '19 at 11:23
  • The function I'm talking about is just called once inside another function's body. – Gixuna Feb 26 '19 at 11:24
  • 1
    In which case the `var myFunction` outside document.ready is redundant. Also note that syntax of the document.ready you're using is deprecated. You should be using `$(document).ready(function() { });` or `$(function() { });` instead. – Rory McCrossan Feb 26 '19 at 11:25
  • Thank you. This is someone else's code: I'm refactoring it and of course going to replace deprecated calls. – Gixuna Feb 26 '19 at 11:27
  • Could be someone's misunderstanding of how javascript is parsed - expecting the function definition *parsing* to be deferred (in an attempt to improve the (perseived) page load time). – freedomn-m Feb 26 '19 at 11:29

0 Answers0