Functions
Functions are reusable blocks of
code that perform a specific task. They help make your code more organized,
readable, and maintainable.
Function
Declaration vs Function Expression
Function Declaration – Defined using the function keyword with a name.
function
greet() {
console.log("Hello, World!");
}
greet();
// Output: Hello, World!
Function Expression – A function stored in a variable (can be anonymous).
const
greet = function() {
console.log("Hello, World!");
};
greet();
// Output: Hello, World!
Parameters
and Return Values
Functions can take inputs (parameters)
and return outputs (return values).
function
add(a, b) {
return a + b;
}
let
sum = add(5, 3);
console.log(sum);
// Output: 8
Arrow
Functions (=>)
Arrow functions provide a shorter
syntax and do not have their own this context.
const
multiply = (x, y) => x * y;
console.log(multiply(4,
5)); // Output: 20
//
Single parameter doesn't need parentheses
const
square = n => n * n;
console.log(square(6));
// Output: 36
Scope:
Local vs Global
- Global Scope
– Variables declared outside any function are accessible anywhere.
- Local Scope
– Variables declared inside a function are accessible only within that
function.
let
globalVar = "I am global";
function
testScope() {
let localVar = "I am local";
console.log(globalVar); // ✅
Accessible
console.log(localVar); // ✅
Accessible here
}
testScope();
console.log(globalVar);
// ✅
Accessible
//
console.log(localVar); // ❌ Error:
not defined
Hoisting
- Function Declarations
are hoisted – they can be called before they are defined in the
code.
- Function Expressions
and Arrow Functions are not hoisted in the same way.
sayHello();
// Works because function declarations are hoisted
function
sayHello() {
console.log("Hello!");
}
//
greet(); // ❌
Error: Cannot access before initialization
const
greet = function() {
console.log("Hi!");
};