Functions
declarations, expressions, arrow functions
Skills taught: js.functions, js.arrow-functions, js.scope, js.closures
Function declaration
// Function declaration — hoisted (can be called before it's defined)
function greet(name) {
return 'Hello, ' + name + '!';
}
console.log(greet('Prashant')); // 'Hello, Prashant!'
console.log(greet('World')); // 'Hello, World!'
// Multiple parameters
function add(a, b) {
return a + b;
}
console.log(add(3, 7)); // 10
// Default parameters
function greetUser(name = 'stranger') {
return `Hello, ${name}!`;
}
console.log(greetUser()); // 'Hello, stranger!'
console.log(greetUser('Prashant')); // 'Hello, Prashant!'
Arrow functions
// Full syntax
const add = (a, b) => {
return a + b;
};
// Implicit return (omit braces and return for single expression)
const add = (a, b) => a + b;
const double = n => n * 2; // one parameter — no parentheses needed
const greet = () => 'Hello'; // no parameters — empty parens required
console.log(add(3, 7)); // 10
console.log(double(5)); // 10
console.log(greet()); // 'Hello'
// Arrow functions are perfect as callbacks
const numbers = [1, 2, 3, 4, 5];
const doubled = numbers.map(n => n * 2); // [2, 4, 6, 8, 10]
Rest parameters and spread
// Rest parameter — collects all remaining arguments into an array
function sum(...numbers) {
return numbers.reduce((total, n) => total + n, 0);
}
console.log(sum(1, 2, 3, 4, 5)); // 15
console.log(sum(10, 20)); // 30
// Spread — expand array/object into individual values
const nums = [3, 1, 4, 1, 5, 9];
console.log(Math.max(...nums)); // 9
const copy = [...nums]; // shallow copy
Functions as values — callbacks
// Functions can be passed as arguments (callbacks)
function runTwice(fn) {
fn();
fn();
}
runTwice(() => console.log('Hello!')); // prints 'Hello!' twice
// DOM event listeners take a callback
document.getElementById('btn').addEventListener('click', (event) => {
console.log('Clicked!', event.target);
});
// setTimeout — run after a delay (ms)
setTimeout(() => console.log('1 second later'), 1000);
Frequently Asked Questions
What is the difference between a function declaration and function expression?
A function declaration (function name() {}) is hoisted — it can be called before its definition in the code. A function expression (const name = function() {}) or arrow function is not hoisted — you must define it before calling it.
When should I use arrow functions vs regular functions?
Use arrow functions for callbacks, array methods, and any function that doesn't need its own 'this'. Use regular functions for methods on objects and constructors — they have their own 'this' binding.
What is a closure?
A closure is a function that 'remembers' variables from the scope where it was created, even after that scope has finished executing. Example: a counter function that keeps its own private count variable.