Function Declaration
A function declaration is a way to define a named function in JavaScript. Functions are one of the fundamental building blocks in JavaScript, allowing you to encapsulate code for reuse and organization.
Syntax
The syntax for declaring a function is straightforward. Here's the basic form:
Examples
Basic Function Declaration
Function with Parameters
Function with Default Parameters
Hoisting
Function declarations are hoisted to the top of their scope, meaning you can call the function before it is defined in the code.
Example of Hoisting
NOTES:
- Hoisting allows functions to be used before they are declared. This can make the code more flexible but can also lead to confusion if not used carefully.
Scope
Functions have their own scope, meaning variables declared within a function are not accessible outside of it.
NOTES:
Local ScopeVariables declared inside a function are local to that function.Global ScopeVariables declared outside any function are in the global scope.
Parameters and Arguments
Parameters
Parameters are placeholders in the function definition.
Arguments
Arguments are the actual values passed to the function when called.
Rest Parameters
Rest parameters allow you to represent an indefinite number of arguments as an array.
NOTES:
Rest ParametersUse rest parameters to handle functions with an unknown number of arguments.Default ParametersProvide default values for parameters to avoid undefined values.
Return Values
Functions can return a value using the return statement.
NOTES:
Return StatementThe return statement ends function execution and specifies a value to be returned.
Best Practices
NOTES:
Use Descriptive NamesFunction names should clearly describe what they do.Keep Functions SmallEach function should perform a single task.Avoid Side EffectsFunctions should avoid modifying global variables or outputting directly to the console.Use Default ParametersProvide default values for parameters to handle unexpected undefined values.KDocument FunctionsUse comments or documentation to describe the purpose and usage of functions.
Example of Best Practices
COMMON MISTAKES:
- Not Using return: Forgetting to use the return statement when a value is expected.
- Overusing Global Variables: Relying too much on global variables can lead to conflicts and bugs.
- Not Handling Edge Cases: Failing to handle edge cases, such as missing arguments or invalid input.
- Ignoring Function Scope: Misunderstanding the scope of variables can lead to unexpected behavior.
Example of Common Mistake
Things to Know
Function HoistingFunction declarations are hoisted to the top of their scope.ScopeRelying too much on global variables can lead to conflicts and bugs.Parameters vs. ArgumentsParameters are in the definition; arguments are in the call.Return StatementEnds function execution and specifies a value to return.