JavaScript Function Definitions
Function Declarations and Function Expressions
JavaScript functions are defined with the function keyword.
JavaScript functions can be defined in different ways.
The most common are function declarations and function expressions.
Function Declarations
A function declaration uses the function keyword and a function name.
Function declarations are loaded before the code runs.
Example
function add(a, b) {
return a + b;
}
add(4, 5);
You can call a function declaration before or after it is written in the code.
Function Expressions
A function expression stores a function inside a variable.
The function can be anonymous (without a name).
Example
const add = function(a, b) {
return a + b;
};
add(4, 5);
Function expressions are executed only when the code reaches them.
Declarations vs Expressions
The difference is when the function becomes available.
Example
add1(4, 5);
function add1(a, b) {
return a + b;
}
Example
add2(4, 5); // Error
const add2 = function(a, b) {
return a + b;
};
In the first example, the function works before it is defined.
In the second example, the function does not exist until the code reaches it.
Why This Happens (Hoisting)
Function declarations are hoisted to the top of their scope.
Function expressions are not hoisted in the same way.
This means:
- Function declarations can be called before they appear
- Function expressions cannot be called before they are defined
Functions Stored in Variables
A function stored in a variable can be used like any other value.
Example
const myFunction = function() {
return "Hello";
};
let text = myFunction();
When to Use Each
- Use function declarations for general-purpose functions
- Use function expressions when assigning functions to variables
- Function expressions are common in callbacks and event handlers
Common Mistakes
Calling a function expression too early
Function expressions must be defined before they are called.Forgetting the semicolon
Function expressions are part of a statement and should end with ;.Confusing function names and variable names
In expressions, the variable name is the function reference.
Next Chapter
Next: Arrow Functions