Introduction
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:
function functionName(parameters) {
// function body
}
Components
NOTES:
functionThe keyword used to declare a function.functionNameThe name of the function, used to call it.parametersOptional. Comma-separated list of input parameters.function bodyThe code to be executed when the function is called.
Examples
Basic Function Declaration
function greet() {
console.log("Hello, World!");
}
// Calling the function
greet(); // Output: Hello, World!
Function with Parameters
function add(a, b) {
return a + b;
}
// Calling the function
console.log(add(2, 3)); // Output: 5
Function with Default Parameters
function multiply(a, b = 1) {
return a * b;
}
// Calling the function
console.log(multiply(5)); // Output: 5 (5 * 1)
console.log(multiply(5, 2)); // Output: 10 (5 * 2)
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
console.log(square(5)); // Output: 25
function square(n) {
return n * n;
}
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.
function sayHello() {
var message = "Hello!";
console.log(message); // Output: Hello!
}
sayHello();
console.log(message); // Error: message is not defined
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.
function example(param1, param2) {
console.log(param1, param2);
}
Arguments
Arguments are the actual values passed to the function when called.
example(1, 2); // Output: 1 2
Rest Parameters
Rest parameters allow you to represent an indefinite number of arguments as an array.
function sum(...numbers) {
return numbers.reduce((acc, num) => acc + num, 0);
}
console.log(sum(1, 2, 3, 4)); // Output: 10
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.
function subtract(a, b) {
return a - b;
}
let result = subtract(10, 5);
console.log(result); // Output: 5
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
/**
* Calculate the area of a rectangle.
*
* @param {number} width - The width of the rectangle.
* @param {number} height - The height of the rectangle.
* @returns {number} - The area of the rectangle.
*/
function calculateArea(width, height) {
return width * height;
}
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
// Mistake: No return statement
function incorrectAdd(a, b) {
a + b;
}
console.log(incorrectAdd(2, 3)); // Output: undefined
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.
