Function Declarations VS Function Expressions in JavaScript




JavaScript provides 2 methods for defining a function: the function declaration and the function expression. In this video we examine the difference, which includes hoisting and the emphasis on first class functions. We also take a look at when you might want to use a named function expression as opposed to an anonymous function expression.

Would you like to help keep this channel going?
https://www.patreon.com/allthingsjavascript

For a complete list of all our tutorials:
http://www.allthingsjavascript.com/youtube.html

Take the Learn Modern JavaScript: Getting Started or the Learn Modern JavaScript: Advanced Topics courses at a huge discount:
https://www.udemy.com/learn-modern-javascript-getting-started/?couponCode=YOUTUBE
https://www.udemy.com/learn-modern-javascript-advanced-topics/?couponCode=YOUTUBE

Original source


25 responses to “Function Declarations VS Function Expressions in JavaScript”

  1. I'm trying to get my head around why it's best to use a function expression in the second example. What is the difference of using a declaration instead?

    function runIt(a) {
    console.log(a);
    a();
    }

    runIt(function() {
    var b = " Now";
    console.log("Running" + b);
    });

    Many thanks!

  2. Also in ES6,

    “`
    console.log(awesomething);
    awesomething();

    const awesomething = () => {
    console.log('Express awesomething');
    }
    “`

    This will return `awesomething is not defined`
    instead of

    “`
    log => undefined
    function => `Uncaught TypeError: something is not a function`

  3. Hi, I just subscribed to your channel, your video was really helpful! I'm confused about one thing though; at 6:15 you say you're going to pass runIt a function expression, but you don't type var in the parentheses, you go straight to typing the word function. However, in the beginning of the video, you mention that by typing function with out the var, it is a function declaration not a function expression. So is what you're passing at 6:15 to runIt a function declaration or function expression? I want to make sure I understand the fundamentals, so thank you for the help, I really appreciate it.

Leave a Reply