1. Understanding Functions
In JavaScript, it's common to define repetitive or similar code blocks that need to be reused multiple times. While loops can handle simple repetition tasks, they are limited in scope. At this point, functions come into play. A function is essentially a block of reusable code that encapsulates a specific task or operation.
2. Using Functions
2.1 Declaring Functions
Using a function involves two steps: defining it and invoking it.
// Function declaration <br></br> function functionName() { <br></br> // Code block <br></br> }
functionis the keyword used to declare a function, and it must be lowercase.- Function names should typically be verbs indicating their purpose, such as
calculateSum.
2.2 Invoking Functions
// Calling the function<br></br> functionName(); // Execute the function body <br></br>
- Always remember to include parentheses when calling a function.
- Remember: a function does not execute unless explicitly invoked.
Note: Defining a function does not run its code. Execution happens only upon invocation.
2.3 Encapsulation of Functions
Encapsulation refers to packaging one or more operations within a function, exposing only a simplified interface to the outside world. Think of it like assembling computer components into a single unit (similar to a packaged shipment).
3. Function Parameters
3.1 Formal vs Actual Parameters
When declaring a function, you can include parameters inside the parentheses, known as formal parameters. When calling the function, values passed in are called actual parameters.
Parameter TypeDescriptionFormal ParameterThe placeholder defined during function creation. These values are unknown until the function is called.Actual ParameterThe real values passed during function call. These are assigned to formal parameters.
Purpose of Parameters: They allow functions to accept dynamic input values during execution.
Example:
// Function with parameters <br></br>function functionName(formalParam1, formalParam2, formalParam3...) { <br></br> // Any number of parameters separated by commas <br></br> // Function body <br></br>} <br></br> // Function call <br></br>functionName(actualParam1, actualParam2, actualParam3...);
3.2 Passing Parameters
// Function definition <br></br>function calculateSum(num1, num2) { <br></br> console.log(num1 + num2); <br></br>} <br></br>// Function calls <br></br>calculateSum(1, 3); // Outputs 4 <br></br>calculateSum(6, 5); // Outputs 11
- Values from actual parameters are passed to formal parameters.
- Formal parameters act like variables that are not declared explicitly.
- Multiple parameters are separated by commas.
3.3 Mismatched Parameter Counts
CaseDescriptionEqual CountsCorrect resultMore Actual Than FormalOnly formal parameters are consideredFewer Actual Than FormalExtra formal parameters become undefined, resulting in NaN
function computeSum(num1, num2) { <br></br> console.log(num1 + num2); <br></br>} <br></br>computeSum(100, 200); // Equal counts, correct output computeSum(100, 400, 500, 700); // Extra parameters ignored <br></br>computeSum(200); // Missing parameter results in NaN
3.4 Summary
- Functions can have zero or more parameters.
- Formal parameters default to
undefinedif no value is passed. - Actual parameters are passed during function invocation.
- Multiple parameters are comma-separated.
- Although mismatched counts are allowed, it's best practice to align them.
4. Return Values in Functions
4.1 The return Statement
Functions may return values to the caller using the return statement.
Syntax:
// Function definition <br></br>function functionName() { <br></br> ... <br></br> return valueToReturn; <br></br>} <br></br>// Function call <br></br>functionName(); // Returns the value specified after return
- When
returnis executed, the function stops and returns the specified value. - If there’s no
return, the function returnsundefined.
Example:
// Function definition <br></br>function calculate() { <br></br> ... <br></br> return 666; <br></br>} <br></br>// Function call <br></br>calculate(); // Returns 666
4.2 Terminating Function Execution
Code after return is not executed.
function add(a, b) { <br></br> return a + b; // Execution stops here <br></br> alert('This will not run'); <br></br>} <br></br>var result = add(21, 6); // Result is 27 <br></br>alert(result);
4.3 Returning Multiple Values
Only one value can be returned. If multiple values are listed with commas, only the last one is effective.
function add(a, b) { <br></br> return a, b; <br></br>} <br></br>var result = add(21, 6); // Result is 6
4.4 Default Return Value
Every function has a return value.
- If a
returnstatemetn exists, it returns the value after it. - If not, the function returns
undefined.
4.5 Difference Between break, continue, and return
break: Exits the current loop.continue: Skips the current iteration and continues the next.return: Exits the function and optionally returns a value.
5. Using arguments
When the number of arguments is unknown, the arguments object can be used. It is an array-like object available inside every function containing all passed arguments.
The arguments object behaves like an array but lacks standard array methods.
6. Two Ways to Declare Functions
1. Named Function Declaration
Declared using the function keyword.
// Definition <br></br>function myFunction() {...} <br></br>// Invocation <br></br>myFunction();
- Also known as a named function.
- Function calls can appear before or after the definition.
2. Anonymous Function Expression
Defined using a function expression.
// Anonymous function expression <br></br>var myFunction = function() {...}; <br></br>// Invocation <br></br>myFunction();
- No name assigned to the function.
- The variable stores the function itself.
- Must be defined before being called.