Functions -> one of the most important concepts in JavaScript.
A function -> a reusable block of code designed to perform a specific task.
Why Use Functions?
โข โ Reuse code
โข โ Reduce duplication
โข โ Improve readability
โข โ Make programs modular
โข โ Easier maintenance
๐ง 1. What is a Function?
Instead of writing the same code multiple times, we -> place it inside a function.
Example:
function greet() {
console.log("Hello World");
}Calling the Function:
โข greet();
Output:
โข Hello World
โก 2. Function Declaration
The most common way -> create a function.
Syntax:
function functionName() {
}Example:
function welcome() {
console.log("Welcome to JavaScript");
}โข welcome();
๐ฅ 3. Function Parameters
Parameters -> variables that receive values.
Example:
function greet(name) {
console.log("Hello " + name);
}โข greet("Deepak");
Output:
โข Hello Deepak
๐ฏ 4. Multiple Parameters
function add(a, b) {
console.log(a + b);
}โข add(10, 20);
Output:
โข 30
๐ 5. Return Statement
return -> sends a value back from a function.
Example:
function add(a, b) {
return a + b;
}let result = add(10, 20);
console.log(result);
Output:
โข 30
๐งฉ 6. Function Expression
A function -> stored inside a variable.
Example:
const greet = function() {
console.log("Hello");
};โข greet();
Difference:
Concept -> Function Declaration vs Function Expression
โข Hoisted -> Yes vs Not Hoisted
โข Defined -> separately vs Stored in variable
โก 7. Arrow Functions (ES6)
Modern way -> write functions.
Traditional Function:
function add(a, b) {
return a + b;
}Arrow Function:
const add = (a, b) => {
return a + b;
};Short Form:
const add = (a, b) => a + b;
๐ฆ 8. Default Parameters
Default values -> used when arguments are not passed.
Example:
function greet(name = "Guest") {
console.log(name);
}โข greet();
Output:
โข Guest
๐ง 9. Rest Parameters
Rest parameters -> collect multiple arguments into an array.
Example:
function sum(...numbers) {
console.log(numbers);
}โข sum(1, 2, 3, 4);
Output:
โข [1, 2, 3, 4]
๐ 10. Scope in JavaScript
Scope -> determines where variables can be accessed.
Global Scope
let name = "Deepak";
function show() {
console.log(name);
}
โข Accessible -> everywhere
Local Scope
function show() {
let age = 25;
console.log(age);
}โข Accessible -> only inside function
๐ 11. Block Scope
Variables -> declared using let and const.
if(true) {
let age = 25;
console.log(age);
}Outside block:
console.log(age);
โ Error
๐ง 12. What is Hoisting?
Hoisting -> JavaScript moves declarations to the top before execution.
Example:
sayHello();
function sayHello() {
console.log("Hello");
}โข Works -> because function declarations are hoisted
๐ฅ 13. Callback Functions
Callback -> function passed as an argument to another function.
Example: