JavaScript for WordPress Forums Vanilla JavaScript Function as variable

Viewing 2 posts - 1 through 2 (of 2 total)
  • Author
  • #15794


    In The basics on functions, 1.2.20, it states that declaring functions as variables is the preferred method. I’m curious why that is?


    var myfunction = function() {
    // do stuff

    rather than

    function myfunction() {
    // do stuff


    Zac Gordon

    Good question.

    I actually went back and forth on what to call the “preferred” method for declaring functions since you will see a lot of functions in JS that are not assigned as variables.

    The added benefit of assigning functions as variables is that you can later change the function assigned to the variable, which is not too common really. However, one extra thing you can do is assign the function to a different variable name if you needed to refer the function as something else in another context.

    Although I do call this preferred here, I have talked to some pros since making the video who don’t feel its usually necessary to take this extra step.

    Hope this unpacks the topic a bit more for you?

Viewing 2 posts - 1 through 2 (of 2 total)
  • You must be logged in to reply to this topic.