| Arrow Functions in JavaScript | Closures in JavaScript | |
Functions, Parameters & Scope in JavaScript |
Default parameters allow you to set a default value for a function parameter.
If no argument is passed, the default value is used.
Default parameters allow functions to have predefined values if no argument is provided.
function greet(name = "Guest") {
return `Hello, ${name}!`;
}
console.log(greet()); // Hello, Guest!
console.log(greet("Alice")); // Hello, Alice!
Rest parameters (...args) allow functions to accept an indefinite number of arguments as an array.
Syntax: function fn(a, b, ...rest) { }
// Example: Rest Parameter
function sum(...numbers) {
let total = 0;
for (let n of numbers) {
total += n;
}
return total;
}
console.log(sum(1, 2, 3)); // 6
console.log(sum(5, 10, 15, 20)); // 50
A named function defined using the function keyword.
function greet(name) {
return `Hello, ${name}!`;
}
A function assigned to a variable.
const greet = function(name) {
return `Hello, ${name}!`;
};
const greet = (name) => `Hello, ${name}!`;
Scope determines where variables and functions are accessible.
let or const inside {}, accessible only inside the block.Scope determines where variables are accessible in your code. JavaScript has three main types of scope:
Variables declared outside any function or block are global and accessible everywhere.
let globalVar = "I'm global";
function showGlobal() {
console.log(globalVar); // Accessible here
}
showGlobal();
console.log(globalVar); // Accessible here too
Variables declared inside a function are local to that function and cannot be accessed outside.
function localScope() {
let localVar = "I'm local";
console.log(localVar); // Accessible here
}
localScope();
// console.log(localVar); ❌ Error: not defined
Variables declared with let or const inside a block { }
are only accessible within that block.
{
let blockVar = "I'm block-scoped";
console.log(blockVar); // Accessible here
}
// console.log(blockVar); ❌ Error: not defined
| Scope | Where Declared | Accessibility |
|---|---|---|
| Global | Outside any function/block | Everywhere in the program |
| Local (Function) | Inside a function | Only inside that function |
| Block | Inside { } with let/const | Only inside that block |
// Function with default & rest parameters
function average(multiplier = 1, ...nums) {
let total = 0;
for (let n of nums) {
total += n;
}
let avg = total / nums.length;
return avg * multiplier;
}
console.log(average(1, 10, 20, 30)); // 20
console.log(average(2, 5, 15)); // 20 (average=10, multiplied by 2)
let and const for block scoping to avoid unexpected behavior. | Arrow Functions in JavaScript | Closures in JavaScript | |