JavaScript Functions
In JavaScript, functions are first-class citizens. This means they can be stored in variables, passed as arguments to other functions, and returned from other functions. Let's break down the three primary ways to define them.
1. Function Declarations
The most traditional way to create a function. It uses the function keyword followed by a name.
Key Trait: Hoisting.
Function declarations are "hoisted" to the top of their enclosing scope. This means you can call the function in your code before you actually declare it.
2. Function Expressions (Anonymous)
Here, we create a function without a name (an anonymous function) and assign it to a variable.
Key Trait: No Hoisting.
Because it's assigned to a variable (especially if using const or let), you cannot call this function before the line where it is defined. The engine will throw an error.
3. Arrow Functions (ES6)
Introduced in ES6 (2015), arrow functions offer a much more concise syntax and handle the this keyword differently (lexical scope).
If your function consists of a single expression, you can utilize the Implicit Return. Drop the curly braces and the return keyword:
When to use which?+
Use Declarations when you want standard, readable top-level functions that can be called from anywhere in the file. Use Expressions when passing callbacks to other functions. Use Arrow Functions for concise mathematical operations, array methods (like map, filter), or when you specifically need to preserve the lexical 'this' binding from the parent scope (like in React class components or setTimeout callbacks).
