JavaScript Functions
Functions are reusable blocks of code that perform specific tasks. Instead of writing the same code multiple times, functions allow developers to reuse code whenever needed.
Functions are one of the most important concepts in JavaScript because modern applications heavily depend on them.
Why Functions are Important?
- Reduce duplicate code
- Improve code organization
- Make programs reusable
- Simplify large applications
- Improve readability and maintenance
Syntax of Function
function functionName(){
// code block
}
Explanation of Syntax
- function keyword creates a function.
- functionName is the function name.
- Curly braces {} contain the function code.
- The function executes only when called.
Basic Function Example
The following example creates a simple function.
function greet(){
console.log("Welcome to JavaScript");
}
greet();
Output
Welcome to JavaScript
Detailed Explanation
- The function name is greet.
- The function stores reusable code.
- greet(); calls the function.
- The message displays after the function executes.
Functions with Parameters
Parameters allow functions to receive values.
function greet(name){
console.log("Hello " + name);
}
greet("Rahul");
Output
Hello Rahul
Explanation
- name is a parameter.
- "Rahul" is passed as an argument.
- The function uses the value dynamically.
Functions with Multiple Parameters
function add(a, b){
console.log(a + b);
}
add(10, 20);
Output
30
Explanation
- The function accepts two parameters.
- 10 and 20 are passed as arguments.
- The + operator performs addition.
Using return Statement
The return statement sends data back from a function.
function multiply(a, b){
return a * b;
}
let result = multiply(5, 4);
console.log(result);
Output
20
Detailed Explanation
- The function multiplies two numbers.
- return sends the result back.
- The returned value is stored inside result variable.
Function Expression
Functions can also be stored inside variables.
let message = function(){
console.log("Function Expression");
};
message();
Output
Function Expression
Arrow Functions
Arrow functions provide a shorter syntax for writing functions.
let greet = () => {
console.log("Arrow Function");
};
greet();
Output
Arrow Function
Explanation
- => is called the arrow operator.
- Arrow functions make code shorter and cleaner.
Default Parameters
Functions can use default parameter values.
function greet(name = "Guest"){
console.log("Hello " + name);
}
greet();
Output
Hello Guest
Explanation
- If no argument is passed, the default value is used.
- This prevents undefined values.
Function Scope
Variables declared inside functions are local variables.
function test(){
let message = "Local Variable";
console.log(message);
}
test();
Output
Local Variable
Explanation
- message exists only inside the function.
- Local variables cannot be accessed outside.
Recursive Function
A recursive function calls itself repeatedly.
function countDown(num){
if(num > 0){
console.log(num);
countDown(num - 1);
}
}
countDown(3);
Output
3 2 1
Explanation
- The function calls itself again and again.
- The recursion stops when the condition becomes false.
Complete Real Life Example
The following example shows a simple student grade calculator using JavaScript functions.
<!DOCTYPE html>
<html>
<head>
<title>JavaScript Functions Example</title>
</head>
<body>
<h2>Student Grade Calculator</h2>
<input type="number"
id="marks"
placeholder="Enter Marks">
<br><br>
<button onclick="calculateGrade()">
Calculate Grade
</button>
<h3 id="output"></h3>
<script>
function calculateGrade(){
let marks =
document.getElementById("marks").value;
let grade = "";
if(marks >= 90){
grade = "Grade A";
}else if(marks >= 70){
grade = "Grade B";
}else if(marks >= 40){
grade = "Grade C";
}else{
grade = "Fail";
}
document.getElementById("output").innerHTML =
"Result: " + grade;
}
</script>
</body>
</html>
Output
Student Grade Calculator Input: 75 Output: Result: Grade B
Detailed Explanation of Example
- The input field accepts student marks.
- The button executes calculateGrade() function.
- The function checks marks using if else conditions.
- The appropriate grade is assigned.
- innerHTML displays the final result dynamically.
- Functions help organize reusable logic cleanly.
Common Mistakes
- Forgetting to call functions.
- Using wrong parameter names.
- Missing return statements.
- Writing functions without proper indentation.
Best Practices
- Use meaningful function names.
- Keep functions short and focused.
- Reuse functions whenever possible.
- Use parameters for dynamic values.
- Write readable and clean code.
Important Notes
- Functions are reusable code blocks.
- Functions execute only when called.
- Parameters receive input values.
- return sends data back from functions.
- Functions improve program structure.
Summary
- Functions store reusable code.
- Functions reduce duplicate code.
- Parameters make functions dynamic.
- return sends values back.
- Arrow functions provide shorter syntax.
- Functions improve code organization.
- Functions are essential in JavaScript development.