Skip to content
blog
2 min read

Function

Learn JavaScript functions: declaring, using them, handling parameters, return values, and hoisting for organized, reusable code.

A function is a reusable block of code. You define it once and call it as many times as you need.

Declaring a Function

function greet(name) {
console.log(`Hello, ${name}!`);
}

Calling a Function

greet("Reza"); // Hello, Reza!
greet("Alice"); // Hello, Alice!

Parameters and Arguments

Parameters are the names in the function definition. Arguments are the values you pass when calling it.

function add(a, b) {
// a and b are parameters
return a + b;
}
add(3, 5); // 3 and 5 are arguments — returns 8

Return Values

return sends a value back to the caller and stops the function:

function square(n) {
return n * n;
}
const result = square(4); // 16

Without return, the function returns undefined.

Default Parameters

function greet(name = "friend") {
console.log(`Hello, ${name}!`);
}
greet(); // Hello, friend!
greet("Reza"); // Hello, Reza!

Hoisting

Function declarations are hoisted — you can call them before they appear in the file:

greet("Reza"); // works fine
function greet(name) {
console.log(`Hello, ${name}!`);
}

Function expressions (const greet = function() {}) and arrow functions are not hoisted.

Functions Are Values

In JavaScript, functions are values. You can store them in variables, pass them to other functions, and return them from functions:

const double = function (n) {
return n * 2;
};
const triple = (n) => n * 3;
[1, 2, 3].map(double); // [2, 4, 6]

This is what makes callbacks, array methods, and patterns like closures possible.