JavaScript Functions
Subject: JavaScript
Functions in JavaScript are reusable blocks of code created to perform a specific task. They improve code readability, modularity, and help reduce repetition.
What is a Function?
A function is a group of statements that performs a task or returns a value. You define it once and can call it multiple times.
Syntax
functionName: Name used to call the functionparameters: Optional values passed into the function
Example 1: Basic Function
Example 2: Function with Parameters
Example 3: Function Expression
Example 4: Arrow Function (ES6+)
Example 5: Default Parameters
Types of Functions
| Type | Description |
|---|---|
| Function Declaration | Declared with the function keyword |
| Function Expression | Stored in a variable |
| Arrow Function | Shorter ES6 syntax |
| Anonymous Function | Function without a name |
| Callback Function | Passed as an argument to another function |
Key Takeaways
- Functions promote reusability and modular design.
- You can use
returnto send a value back. - JavaScript supports default parameters.
- Functions can be passed around as first-class citizens.
- Choose between declaration, expression, or arrow functions based on use case.