JavaScript for WordPress Forums Vanilla JavaScript 1.2.20 – Introduction to Functions – Hoisting

Viewing 2 posts - 1 through 2 (of 2 total)
  • Author
  • #26791
    Jeremy Englert

    Near the end of 1.2.20, it is mentioned that a function declaration always must be made before a function call, however, this isn’t necessarily true.

    A function expression must always be declared before a function call. But a regular function declaration can be made after a function call.

    For example, this code will fail.

    var log = function() {
      console.log("Hoisting is nuts");

    This code will run fine.

    function log() {
      console.log("Hoisting is nuts");

    While this probably isn’t common, it’s helpful to know when reading others code. I only bring this up because it was definitely something that has caused me some headaches in the past. Hopefully this can be helpful to someone. 🙂

    Zac Gordon

    Great point Jeremy!

    We are going to get into scoping and hoisting in our advanced JS topics, but you are right on point there and it’s a good thing to mention about seeing it in other people’s code (even some of my examples in this course).

    I couldn’t really find a concensus on plain function declaration v expression and variable assignment, but if using the former it’s best to wrap your code in an IIFE to avoid it being hosted all the way to global scope.

    It’s kind of similar to what happens when you assign a variable without using var, which is why I felt the named function expression was a little “stricter” in some way so possibly better to encourage.

    Since making those videos I have talked with folks who say just regular function declarations are fine if in an IIFE.

    Thanks for bringing up this whole topic and good point that I didn’t mention in the videos. Looking forward to digging into this deeper very soon 🙂

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