What is a Function?
- A function in JavaScript is a reusable block of code designed to perform a specific task. Functions are executed when they are called or invoked
- Instead of writing the same code multiple times, we can define it once and reuse it.
Why Use Functions?
✅ Code reusability
✅ Better readability
✅ Easy debugging
✅ Modular programming
Basic Syntax
function functionName(parameters) {
// code
return value;
}
Example
function greet(name) {
return "Hello " + name;
}
console.log(greet("Akalya"));
Output:
Hello Akalya
Types of Functions in JavaScript
function add(a, b) {
return a + b;
}
✔️ Can be called before declaration (hoisting)
2. Function Expression
const add = function(a, b) {
return a + b;
};
- A function expression is a function stored in a variable
- The variable name can be used to call the function
- Cannot be called before declaration
3. Arrow Function (ES6)
const add = (a, b) => a + b;
- Arrow Functions is a short syntax for function expressions
- You can skip the function keyword
- You can skip the return keyword
- You can skip the curly brackets
4.Anonymous Function(Need to be discussed)
setTimeout(function() {
console.log("Hello");
}, 1000);
Function without a name
5. Immediately Invoked Function (IIFE)(Need to be discussed)
(function() {
console.log("Runs immediately");
})();
Executes as soon as it is defined
Parameters vs Arguments
function add(a, b) { // parameters
return a + b;
}
add(2, 3); // arguments
Function Parameters
- Parameters allow you to send values to a function
- Parameters are listed in parentheses in the function definition
Function Arguments
- Function parameters and arguments are distinct concepts
- Parameters are the names listed in the function definition
- Arguments are the values received by the function
Return Statement
- Used to send value back from function
- Stops execution after returning
function square(n) {
return n * n;
}
Default Parameters
function greet(name = "Guest") {
return "Hello " + name;
}
Function Scope
- Variables inside function → local scope
- Variables outside → global scope
let x = 10;
function test() {
let y = 20;
console.log(x); // accessible
}
Callback Functions(Need to be discussed)
Function passed as argument to another function
function greet(name, callback) {
console.log("Hi " + name);
callback();
}
function sayBye() {
console.log("Bye!");
}
greet("Akalya", sayBye);
Higher Order Functions(Need to be discussed)
Functions that:
Take another function as argument OR
Return a function
Example: map(), filter()

Top comments (0)