Create a function in JavaScript
In JavaScript, there are three primary ways to create a function: Function Declaration, Function Expression, and Arrow Function.
- Function Declaration:
Example Code:
Characteristics: One of the major features of function declarations are hoisted to the top of their scope. Which mean, you can call a function before it’s defined in the code, and it will still work.
- Function Expression:
Example Code:
Characteristics: Function expressions are NOT hoisted to the top of their scope. Which mean, you can NOT call a function before it’s defined in the code.
Function expressions are commonly used as Callbacks arguments to other functions or in situations where you need to define a function dynamically.
- Arrow Function (ES6+):
More concise syntax for writing functions, especially for small, simple functions. Arrow functions are always anonymous.
Example Code:
Characteristics: Arrow functions don’t have their own this
context.
Example of Anonymous Function:
In this case, the anonymous function has no name, but it is stored in the multiply
variable, so you can call it through the variable.
Summary:
Feature | Function Declaration | Function Expression | Arrow Function |
---|---|---|---|
Hoisting | Yes | No | No |
Anonymous | No | Can be | Always anonymous |
this binding | Dynamic | Dynamic | Lexical |
Arguments object | Yes | Yes | No (use rest parameters) |
Use cases | General purpose, hoisted | Dynamic, callbacks | Concise functions, this context |
Do you enjoy this blog post?