Function Declarations & Expressions
Functions are reusable blocks of code. They take input (parameters), process it, and return output. Functions are the building blocks of any JavaScript application — they organize code, avoid repetition, and make programs maintainable.
Function Types
- Function Declaration — function greet() { }. Hoisted, can be called before defined
- Function Expression — const greet = function() { }. Not hoisted, must be defined first
- Named vs Anonymous — Named expressions help with debugging: const greet = function greet() { }
- Functions as values — JavaScript functions are 'first-class': can be stored in variables, passed as arguments, returned from other functions
- DRY principle — Don't Repeat Yourself. Extract repeated code into functions
Functions Code
// Function Declaration (hoisted — can call before definition)
console.log(greet("Alice")); // Works! Declarations are hoisted
function greet(name) {
return "Hello, " + name + "!";
}
// Function Expression (NOT hoisted)
const add = function(a, b) {
return a + b;
};
console.log(add(5, 3)); // 8
// Functions are values — can be stored in variables
const math = {
add: function(a, b) { return a + b; },
subtract: function(a, b) { return a - b; }
};
console.log(math.add(10, 5)); // 15
console.log(math.subtract(10, 5)); // 5
// Real-world: format currency
function formatPrice(price) {
return "₹" + price.toFixed(2);
}
console.log(formatPrice(99)); // ₹99.00
console.log(formatPrice(49.5)); // ₹49.50Tip
Tip
Start with function declarations for top-level functions (they're hoisted, so order doesn't matter). Use arrow functions for callbacks and inline operations. This convention makes your code's intent clear at a glance.
Function + environment.
Common Mistake
Warning
Calling a function expression before it's defined. Unlike declarations, const greet = function() {} is NOT hoisted. If you call greet() before that line, you get 'greet is not a function'. Define expressions before calling them.
Practice Task
Note
Create three versions of the same function: (1) A function declaration that calculates area (length * width). (2) A function expression stored in a const. (3) Test hoisting by calling the declaration before its definition line.
Quick Quiz
Key Takeaways
- Functions are reusable blocks of code.
- Function Declaration — function greet() { }. Hoisted, can be called before defined
- Function Expression — const greet = function() { }. Not hoisted, must be defined first
- Named vs Anonymous — Named expressions help with debugging: const greet = function greet() { }