3.1 Declaring Functions
Functions are one of the main building blocks in JavaScript. They allow you to organize code, reuse logic, and create more complex structures. Let's look at three main ways to declare and use functions: function declarations, function expressions, and arrow functions.
Function Declaration is a way to create a named function that you can call later. These functions are "hoisted" to the top of their scope, allowing them to be called before they are declared in the code.
Syntax:
function name (arguments) {
// function body
}
Example Usage:
// Function Declaration
function greet(name) {
return `Hello, ${name}!`;
}
// Function Call
console.log(greet('Alice')); // Outputs: Hello, Alice!
3.2 Function Expressions
Function expressions create anonymous functions (functions without a name) that can be assigned to a variable. These functions are not "hoisted," so they can only be called after they are declared.
Syntax:
const name = function (arguments) {
// function body
}
Example Usage:
// Function Expression
const greet = function(name) {
return `Hello, ${name}!`;
};
// Function Call
console.log(greet('Bob')); // Outputs: Hello, Bob!
3.3 Arrow Functions
Arrow Functions are a concise way to declare functions, and they also preserve the this context from their parent scope. Arrow functions don't have their own this, which is particularly useful for event handlers and array methods.
Syntax:
const name = (arguments) => {
// function body
}
If a function takes one parameter, the parentheses can be omitted. If a function returns a single expression, curly braces and the return keyword can be omitted.
Example 1: Full Version
// Arrow Function
const greet = (name) => {
return `Hello, ${name}!`;
};
// Function Call
console.log(greet('Charlie')); // Outputs: Hello, Charlie!
Example 2: Short Version
// Arrow function with one parameter and one expression
const greet = name => `Hello, ${name}!`;
// Function Call
console.log(greet('Dana')); // Outputs: Hello, Dana!
3.4 Comparing Ways to Declare Functions
Hoisting:
- Function Declarations: functions are hoisted, allowing them to be called before they are declared
- Function Expressions and Arrow Functions: are not hoisted, and can only be called after being declared
this Context:
- Function Declarations and Function Expressions: have their own
thiscontext - Arrow Functions: do not have their own
this, the context is inherited from the parent scope
Writing Convenience:
- Arrow Functions: are more concise and are often used for short functions and callbacks
GO TO FULL VERSION