Functions
Functions are blocks of code that perform specific tasks and can be reused throughout a program. They help in organizing code, making it modular, and reducing redundancy.
What is a Function?
A function is a reusable block of code that performs a specific task. Functions typically take input, process it, and return an output. The general structure of a function includes:
- Function name: Identifies the function.
- Parameters: Input values the function uses (optional).
- Return type: The value the function sends back as output (optional).
- Function body: The code that runs when the function is called.
Functions in Different Languages
- JavaScript
- Java
- Python
- C++
JavaScript Functions Overview
JavaScript supports both function declarations and expressions.
Video Explanation

Function Declaration
Declaring a function in JavaScript
function greet(name) {
return `Hello, ${name}!`;
}
console.log(greet("Alice")); // Output: Hello, Alice!
Function Expression
Function expression in JavaScript
const greet = function(name) {
return `Hello, ${name}!`;
};
console.log(greet("Bob")); // Output: Hello, Bob!
Arrow Functions
Introduced in ES6, arrow functions provide a concise way to write functions.
Arrow function in JavaScript
const greet = (name) => `Hello, ${name}!`;
console.log(greet("Charlie")); // Output: Hello, Charlie!
Function Scope and Closures
Functions in JavaScript can create closures, capturing variables from their surrounding scope.
Function scope and closures in JavaScript
function outerFunction() {
let outerVar = "I'm outer";
function innerFunction() {
console.log(outerVar); // Can access outerVar
}
return innerFunction;
}
const inner = outerFunction();
inner(); // Output: I'm outer