So far, you have learned how to create functions using the function keyword. Another powerful way to create functions in JavaScript is using function expressions.
In a function expression, a function is stored inside a variable. This allows functions to be treated like any other value, making JavaScript more flexible and powerful.
Function expressions are commonly used in modern JavaScript, especially in callbacks and event handling.
Function Declaration vs Function Expression
Function Declaration:
- Uses the function keyword with a name
- Can be called before it is defined
Function Expression:
- Stores a function inside a variable
- Can only be used after it is defined
Both are useful, but function expressions give more control in many situations.
This is a normal function declaration. The function has a name and can be called anywhere in the code.
Here, the function is stored in the variable greet. The function runs when the variable is called.
This makes functions behave like variables, which is very useful in modern JavaScript.
This example shows how function expressions are used to perform calculations and return values.
By mastering function expressions, students gain flexibility in writing JavaScript programs and prepare themselves for advanced concepts like callbacks and arrow functions.