JavaScript Functions
Learn how to create reusable functions, pass parameters, return values, use function expressions and write arrow functions with practical examples.
1. What Is a Function in JavaScript?
A function is a reusable block of code designed to perform a particular task. We write the code inside a function and execute it whenever required by calling that function.
Suppose we want to display a welcome message ten times. Instead of writing
the same console.log() statement ten times, we can create a
function and call it whenever we need the message.
Why Do We Need Functions?
- Code Reusability: Write code once and use it multiple times.
- Less Duplication: Avoid writing the same statements repeatedly.
- Easy Maintenance: Update the logic in one place.
- Better Organization: Divide a large program into smaller tasks.
- Easy Testing: Test individual functions separately.
2. Function Working Diagram
A function generally follows three steps: define the function, call it, and execute the statements inside it.
Function Definition
function greet() { ... }
Define the task that the function will perform.
Function Call
greet();
Call the function to execute its code.
Function Execution
console.log("Welcome!");
The statements inside the function execute.
3. Function Declaration and Syntax
A function declaration uses the function keyword followed by
the function name, parentheses and a block of code.
function functionName() {
// Statements to execute
}
functionName();
Understanding the Syntax
| Syntax | Meaning |
|---|---|
function |
Keyword used to declare a function. |
functionName |
The name used to identify and call the function. |
() |
Parentheses contain the function parameters, if any. |
{ } |
The function body contains the statements to execute. |
functionName() |
Calls the function. |
4. Simple Function Example
Let's create a function that displays a welcome message.
function greet() {
console.log("Welcome to CIIT Training Institute!");
}
greet();
greet();
Expected Output
Welcome to CIIT Training Institute! Welcome to CIIT Training Institute!
Explanation
- The
greet()function is declared. - The message is written inside the function body.
- The first call executes the function and displays the message.
- The second call executes the same function again.
We have written the message only once, but we can execute it multiple times. This is the main advantage of a function.
5. Function Parameters and Arguments
Functions can accept values so that the same function can work with different inputs.
- Parameter: A variable specified in the function definition.
- Argument: A value supplied when the function is called.
function greetStudent(name) {
console.log("Hello, " + name + "!");
}
greetStudent("Samadhan");
greetStudent("Pradnya");
Expected Output
Hello, Samadhan! Hello, Pradnya!
Parameter and Argument Diagram
greetStudent("Samadhan")
name = "Samadhan"
Hello, Samadhan!
Here, name is the parameter. The strings
"Samadhan" and "Pradnya" are arguments.
6. Function with Multiple Parameters
A function can accept multiple parameters separated by commas. For example, an addition function can accept two numbers.
function add(a, b) {
console.log(a + b);
}
add(10, 20);
add(50, 30);
Expected Output
30 80
How Values Are Assigned
| Function Call | Parameter a | Parameter b | Result |
|---|---|---|---|
add(10, 20) |
10 | 20 | 30 |
add(50, 30) |
50 | 30 | 80 |
7. Return Statement in JavaScript
The return statement sends a value back to the code that
called the function. This value can be stored in a variable, printed,
or used in another calculation.
function add(a, b) {
return a + b;
}
let result = add(10, 20);
console.log(result);
Expected Output
30
Understanding the Return Value
add(10, 20)calls the function.- The function calculates
10 + 20. return a + bsends back the value30.- The returned value is stored in
result. console.log(result)displays the value.
undefined. The return statement also
ends the current function execution.
Difference Between console.log() and return
| console.log() | return |
|---|---|
| Displays a value in the console. | Sends a value back to the caller. |
| Does not automatically return that displayed value. | The returned value can be stored and reused. |
| Useful for displaying information and debugging. | Useful for calculations and further processing. |
8. Default Parameters
A default parameter provides a fallback value when an argument is omitted
or its value is undefined.
function greet(name = "Student") {
console.log("Hello, " + name);
}
greet("Samadhan");
greet();
Expected Output
Hello, Samadhan Hello, Student
When greet("Samadhan") is called, the supplied value is used.
When greet() is called without an argument, the default value
"Student" is used.
9. Function Expression
A function expression creates a function and assigns it to a variable. The function can be called through that variable.
const subtract = function(a, b) {
return a - b;
};
let result = subtract(20, 8);
console.log(result);
Expected Output
12
Here, the function is assigned to the variable subtract.
We use subtract(20, 8) to execute it.
const variable. The variable cannot be reassigned,
but the function can still be called.
10. Arrow Functions
An arrow function is a concise way to write a function expression.
It uses the => operator.
const add = (a, b) => {
return a + b;
};
console.log(add(10, 15));
Expected Output
25
Short Arrow Function
When an arrow function contains a single expression and does not use braces, the expression's result is returned automatically.
const square = number => number * number;
console.log(square(5));
Expected Output
25
Function Types Comparison
| Type | Example Syntax | Usage |
|---|---|---|
| Function Declaration | function add(a, b) { ... } |
Named reusable functions. |
| Function Expression | const add = function(a, b) { ... }; |
Assign a function to a variable. |
| Arrow Function | const add = (a, b) => a + b; |
Concise function expressions. |
11. Practical Example: Calculate Student Marks
In this example, one function calculates total marks and another calculates the average. The returned value from the first function is passed to the second.
function calculateTotal(mark1, mark2, mark3) {
return mark1 + mark2 + mark3;
}
function calculateAverage(total) {
return total / 3;
}
let total = calculateTotal(80, 75, 90);
let average = calculateAverage(total);
console.log("Total Marks: " + total);
console.log("Average Marks: " + average.toFixed(2));
Expected Output
Total Marks: 245 Average Marks: 81.67
Step-by-Step Execution
calculateTotal(80, 75, 90)calculates the total.- The total value
245is returned. - The returned value is passed to
calculateAverage(total). - The average is calculated by dividing
245by3. toFixed(2)formats the average to two decimal places.
12. Function Return Flow Diagram
This diagram shows how input values move through a function and how the returned result is used by the calling code.
calculateTotal(80, 75, 90)
80 + 75 + 90 = 245
return 245;
Total Marks: 245
13. Common Mistakes in Functions
| Common Mistake | Correct Understanding |
|---|---|
| Defining a function but never calling it. | Call the function to execute its body. |
Expecting console.log() to return a result. |
Use return when the caller needs a value. |
| Passing arguments in the wrong order. | Pass arguments in the intended parameter order. |
| Forgetting parentheses when calling a function. | Use functionName() to call a regular function. |
| Writing code after an unconditional return statement. | Place required statements before the return statement. |
| Using braces in an arrow function but forgetting return. | Use an explicit return inside a block body. |
14. Practice Tasks
Task 1: Calculate Rectangle Area
Create a function named calculateArea that accepts
length and width and returns the rectangle's area.
- Accept two parameters: length and width.
- Calculate area using
length * width. - Return the calculated value.
- Call the function with length 10 and width 5.
- Display the result using
console.log().
Area: 50
Task 2: Check Even or Odd
Create a function named checkEvenOdd that accepts
a number and returns whether the number is even or odd.
- Accept one parameter.
- Use the modulus operator
%. - Return an appropriate message.
- Test the function with
10and7.
10 is Even
7 is Odd
Task 3: Convert Celsius to Fahrenheit
Create a function that accepts a temperature in Celsius and returns the Fahrenheit temperature.
Formula:Fahrenheit = (Celsius * 9 / 5) + 32
Fahrenheit: 77
Summary
JavaScript functions help us organize code into reusable blocks that can perform specific tasks.
- A function is defined and then called to execute its code.
- Parameters receive the input values supplied as arguments.
- Functions can accept multiple parameters.
- The
returnstatement sends a value back to the caller. - Default parameters provide fallback values.
- Function expressions assign functions to variables.
- Arrow functions provide a concise way to write function expressions.
- Functions improve code reuse, readability and maintainability.