iti
15 April 2025
๐ง Introduction to Functions in JavaScript
Functions in JavaScript are blocks of reusable code that perform a specific task. Instead of writing the same code multiple times, we can create a function and call it wherever needed.
๐ What is a Function?
A function is a self-contained block of code that can be executed when it is called or invoked.
โ Syntax of a Function
function functionName(parameters) {
// code to be executed
}
๐งช Example:
function greetUser(name) {
console.log("Hello, " + name + "!");
}
greetUser("Rahul"); // Output: Hello, Rahul!
๐งฑ Types of Functions in JavaScript
1. ๐ User-defined Functions
Functions created by the user to perform specific tasks.
function add(a, b) {
return a + b;
}
console.log(add(5, 3)); // Output: 8
2. ๐ Built-in Functions
JavaScript provides many pre-defined functions like:
parseInt()
alert()
prompt()
Math.round()
3. ๐ Anonymous Functions
Functions without a name, usually assigned to a variable.
let show = function() {
console.log("Anonymous Function");
};
show();
4. ๐ Arrow Functions (ES6)
Shorter syntax for writing functions.
const multiply = (x, y) => x * y;
console.log(multiply(4, 5)); // Output: 20
๐ Function Parameters and Arguments
- Parameters: Names listed in the function definition.
- Arguments: Actual values passed to the function.
function subtract(x, y) {
return x - y;
}
console.log(subtract(10, 4)); // 6
๐ Return Statement
Functions can return values using the return
keyword.
function square(n) {
return n * n;
}
console.log(square(6)); // Output: 36
๐ Advantages of Using Functions
- โ Code reusability
- โ Better code organization
- โ Easier debugging and maintenance
- โ Improves program readability
๐ Summary
- Functions are reusable blocks of code in JavaScript.
- They can accept inputs (parameters) and return outputs.
- Arrow functions and anonymous functions offer advanced ways to define functions.
- Using functions helps in writing cleaner and more efficient code. ๐ง ๐ป