JavaScript Functions
What Is a Function?
A function is a block of reusable code that performs a specific task. You define it once and use it whenever needed.
Functions make your code cleaner, modular, and easier to debug.
Declaring Functions
You can declare a function using the function
keyword:
function greet() {
console.log("Hello, world!");
}
greet(); // Calling the function
Function with Parameters:
function greetUser(name) {
console.log("Hello, " + name + "!");
}
greetUser("Alice"); // Output: Hello, Alice!
Function with Return:
function add(a, b) {
return a + b;
}
let result = add(3, 5); // result is 8
Arrow Functions
Arrow functions offer a shorter syntax and are commonly used in modern JavaScript.
Syntax:
const add = (a, b) => a + b;
Example:
const sayHello = () => {
console.log("Hi there!");
};
sayHello(); // Output: Hi there!
Arrow functions are best for simple, short functions.
Function Parameters and Return Values
Functions can accept inputs (called parameters) and return outputs (using return
).
function multiply(x, y) {
return x * y;
}
let product = multiply(4, 5); // 20
- You can pass any type of value: strings, numbers, arrays, objects, even other functions.
- If no
return
is used, the function returnsundefined
by default.
Callback Functions
A callback is a function passed as an argument to another function — often used in asynchronous code (like setTimeout
, fetch
, etc.).
Example:
function greet(name) {
console.log("Hello, " + name);
}
function processUser(callback) {
let username = "John";
callback(username);
}
processUser(greet); // Output: Hello, John
You can also pass anonymous functions or use arrow functions as callbacks.
Scope and Hoisting
Scope
Scope defines where variables are accessible.
- Global Scope: Available everywhere.
- Function Scope: Available only inside the function.
- Block Scope (
let
,const
only): Limited to{ }
blocks.
let globalVar = "I'm global";
function testScope() {
let localVar = "I'm local";
console.log(globalVar); // Accessible
console.log(localVar); // Accessible
}
console.log(globalVar); // Accessible
// console.log(localVar); // ❌ Error: not defined
Hoisting
Function declarations are hoisted, meaning you can call them before they appear in the code:
sayHello();
function sayHello() {
console.log("Hello!");
}
But function expressions and arrow functions are not hoisted:
greet(); // ❌ Error: Cannot access 'greet' before initialization
const greet = () => {
console.log("Hi!");
};
Summary
- Use functions to organize and reuse code.
- Prefer arrow functions for short, clean expressions.
- Functions can take parameters and return values.
- Callbacks let you pass one function into another.
- Understand scope to avoid accidental variable access.
- Function declarations are hoisted, but expressions and arrow functions are not.