Difference between function expression vs declaration in JavaScript
Function Declaration:
A Function Declaration( or a Function Statement) defines a function with the specified parameters without requiring a variable assignment. They exist on their own, i.e, they are standalone constructs and cannot be nested within a non-function block. A function is declared using the function keyword.
-
Syntax:
function gfg(parameter1, parameter2) { //A set of statements }
Function Expression:
A Function Expression works just like a function declaration or a function statement, the only difference is that a function name is NOT started in a function expression, that is, anonymous functions are created in function expressions. The function expressions run as soon as they are defined.
-
Syntax:
var gfg = function(parameter1, parameter2) { //A set of statements }
Example 1: Using a Function Declaration
<!DOCTYPE html> <html> <head> <title>Function Declaration</title> </head> <body> <center> <h1 style="color:green">GeeksforGeeks</h1> <h3>Function Declaration</h3> <script> function gfg(a, b) { return a * b; } var result = gfg(5, 5); document.write(result); </script> </center> </body> </html> |
Output:
25
Example 2: Using a Function Expression
<!DOCTYPE html> <html> <head> <title>Function Expression</title> </head> <body> <center> <h1 style="color:green">GeeksforGeeks</h1> <h3>Function Expression</h3> <script> var gfg = function(a, b) { return a * b; } document.write(gfg(5, 5)); </script> </center> </body> </html> |
Output:
25
Recommended Posts:
- Difference between Definition and Declaration
- JavaScript | RegExp [^abc] Expression
- JavaScript | RegExp [0-9] Expression
- JavaScript | RegExp [^0-9] Expression
- JavaScript | RegExp [abc] Expression
- JavaScript | RegExp (x|y) Expression
- Difference between Anonymous Inner Class and Lambda Expression
- How to validate URL using regular expression in JavaScript?
- Difference between var and let in JavaScript
- Difference between JavaScript and Php
- Difference between TypeScript and JavaScript
- Difference between Java and JavaScript
- Difference between == and === operator in JavaScript
- Difference between substr() and substring() in JavaScript
- What is the difference between call and apply in JavaScript?
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



