| JavaScript: Break & Continue | Arrow Functions in JavaScript | |
JavaScript: Functions & Scope: Declarations & Expressions |
A function is a reusable block of code designed to perform a specific task. Functions help make code modular, readable, and reusable.
A function declaration defines a named function using the function keyword.
It is hoisted, meaning you can call it before it is defined in the code.
// Function Declaration
function greet(name) {
return "Hello, " + name + "!";
}
// Can be called before declaration (hoisting)
console.log(greet("Shivshanker")); // Hello, Shivshanker!
A function expression defines a function inside an expression and assigns it to a variable. It is not hoisted, so it can only be called after it is defined.
// Function Expression
const greetUser = function(name) {
return "Hi, " + name + "!";
};
// Must be called after definition
console.log(greetUser("Shivshanker")); // Hi, Shivshanker!
| Feature | Function Declaration | Function Expression |
|---|---|---|
| Syntax | function name() { } |
const fn = function() { } |
| Hoisting | ✅ Can be called before definition | ❌ Cannot be called before definition |
| Name | Always has a name | Can be anonymous or named |
| Use Case | Good for defining reusable functions globally | Good for inline functions, callbacks |
Scope defines where variables and functions are accessible:
let or const inside { } are only accessible within that block.
function testScope() {
let localVar = "I'm local";
console.log(localVar); // Accessible here
}
// console.log(localVar); ❌ Error: not defined
// Function Declaration
function greetMorning(name) {
return "Good Morning, " + name + "!";
}
// Function Expression
const greetEvening = function(name) {
return "Good Evening, " + name + "!";
};
console.log(greetMorning("Alice")); // Good Morning, Alice!
console.log(greetEvening("Bob")); // Good Evening, Bob!
| JavaScript: Break & Continue | Arrow Functions in JavaScript | |