JavaScript function expression | Benefits and Examples

A JavaScript function expression is a way of defining a function. Even function expression can be stored in a variable. It can be to be stored in a variable and can be accessed using variableName. 


JavaScript function expression Examples

HTML example code variable can be used as a function in JavaScript.

Anonymous function (without name)


JavaScript function expression example

Named function Expression

Output: Multiplication : 49

Arrow Function

Output: Division : 7

Benefits of function expressions

A function expressions useful when:-

  • As closures
  • As Immediately Invoked Function Expressions (IIFE)
  • As arguments to other functions
  • A function expression can be stored in a variable:

Q: Why use named function expressions?

Answer: You should always use named function expressions, that’s why:

  1. You can use the name of that function when you need recursion.
  2. Anonymous functions don’t help when debugging as you can’t see the name of the function that causes problems.
  3. It’s harder to understand if you do not name a function.

Do comment if you have any doubts and suggestion on this topic.

Note: All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.