DEV Community

Discussion on: A Simple Guide to JavaScript Functions - Native, Arrow and Shorthand.

Collapse
 
lucassperez profile image
Lucas Perez • Edited

I'm very new to JS, so I'm probably missing something, but is there an advantage to using a function expression instead of a regular function declaration? Assuming we're not using the arrow.
I mean, between:

function add(number1, number 2) {
    return number1 + number2;
}
Enter fullscreen mode Exit fullscreen mode

And

const add = function (number1, number2) {
    return number1 + number2;
}
Enter fullscreen mode Exit fullscreen mode

Are there practical differences?
Maybe I can hoist the second if I use a var declaration and that is desirable?

Collapse
 
codingnninja profile image
Ayobami Ogundiran • Edited

I like this question because it feels like what I should have explained in the write-up.

Function expressions are not hoisted even when we use them with "var";

Thanks for raising the question.

The practical differences could be:

  1. We can't define or declare a regular functions in a conditional statement like if it is necessary to do so (but it is rarely necessary if not impossible), in that case we have to use function expression.
(function() {
  'use strict';
  if (true) {
    function going() {
      return 'yes';
    }
  } else {
    function notGoing() {
      return 'no';
    }
  }
  console.log(typeof going === 'undefined'); // => true
  console.log(going()); // Throws "ReferenceError: going is not defined"
})();
Enter fullscreen mode Exit fullscreen mode

We will use function expression to make it work.

Note: Declaring a function in a conditional statement is not recommended or should be avoided.

2 . It is easy to pass a function expression around so it is used to create modules without worrying about polluting the global scope before the introduction of import and export.

Collapse
 
lucassperez profile image
Lucas Perez

Thanks very much! Very nice text (: