A JavaScript function is a reusable block of code designed to perform a task. A function can accept input through parameters, execute statements, and optionally return a value to the code that called it.
Basic syntax:
function functionName(parameter) {
// statements
return value;
}
Simple example:
function greet(name) {
return `Hello, ${name}!`;
}
console.log(greet("Asha")); // Hello, Asha!
Here name is a parameter, "Asha" is an argument, and return sends the completed string back to the caller.
Defining a function tells JavaScript what the function should do. It does not run the function. Add parentheses after the function name to call it.
function showMessage() {
console.log("Welcome to plus2net");
}
showMessage(); // function call
This preserves the purpose of the original first example while replacing the old document.write() output with a modern, non-destructive example.
Parameters are variable names written in the function definition. Arguments are the actual values supplied when the function is called.
function welcome(siteName) {
console.log(`Welcome to ${siteName}`);
}
welcome("plus2net");
A function can accept several parameters.
function add(a, b) {
return a + b;
}
console.log(add(5, 8)); // 13
JavaScript does not enforce parameter types by default. Your code is responsible for validating values when the type matters.
return ends the current function call and sends a value back to the expression that called the function.
function multiply(a, b) {
const result = a * b;
return result;
}
const total = multiply(4, 6);
console.log(total); // 24
Statements after a reached return do not execute.
If execution reaches the end of a normal function without a return value, the result of the call is undefined.
function logGreeting() {
console.log("Hello");
}
const result = logGreeting();
console.log(result); // undefined
That is fine for a function whose purpose is to perform an action rather than calculate a result.
A default parameter is used when the caller omits the argument or explicitly supplies undefined.
function greet(name = "Guest") {
return `Hello, ${name}`;
}
console.log(greet()); // Hello, Guest
console.log(greet("Ravi")); // Hello, Ravi
A rest parameter collects remaining arguments into a real array. Only one rest parameter is allowed, and it must be the last parameter.
function sum(...numbers) {
let total = 0;
for (const number of numbers) {
total += number;
}
return total;
}
console.log(sum(2, 4, 6)); // 12
Functions are values in JavaScript. A function expression can be assigned to a variable and called through that variable.
const square = function (number) {
return number * number;
};
console.log(square(5)); // 25
Unlike a function declaration, a function expression assigned to const cannot be called before that declaration has been initialized.
Arrow functions provide a shorter function-expression syntax. A single expression can be returned implicitly.
const double = (number) => number * 2;
console.log(double(7)); // 14
Arrow functions do not have their own this, arguments, super, or new.target, and they cannot be used as constructors. Choose them when that behavior is appropriate rather than treating them as a universal replacement for normal functions.
The original page demonstrated local and global variables several ways. Those distinctions are important and should remain explicit.
A local variable can hide a variable with the same name outside the function:
const value = 5;
function showValue() {
const value = 2;
console.log(value); // 2
}
showValue();
console.log(value); // 5
A function can read variables from an outer scope:
const siteName = "plus2net";
function showSite() {
console.log(siteName);
}
showSite(); // plus2net
Variables declared with let and const are also block-scoped inside blocks such as if and for. See JavaScript variables for more on declaration and scope.
An inner function can access variables from its outer function even after the outer function has finished. This relationship is called a closure.
function makeCounter() {
let count = 0;
return function () {
count++;
return count;
};
}
const counter = makeCounter();
console.log(counter()); // 1
console.log(counter()); // 2
Closures are a fundamental JavaScript feature used for private state, callbacks, event handlers, and many module patterns.
Function declarations are hoisted within their scope, so they can be called before their declaration appears in the source.
console.log(square(5)); // 25
function square(number) {
return number * number;
}
Do not assume the same behavior for a function expression stored in let or const; it cannot be called before the variable is initialized.
Arguments are passed by value. For objects, the value being passed is a reference to the object, so changing one of the object's properties inside the function is visible through other references to the same object.
function renameUser(user) {
user.name = "Anita";
}
const person = { name: "Ravi" };
renameUser(person);
console.log(person.name); // Anita
Reassigning the parameter itself does not replace the caller's variable. The same principle applies when an array is passed and its elements are changed.
Traditional non-arrow functions have an array-like arguments object containing supplied arguments. Modern code often prefers rest parameters because they create a real array and make the intended inputs clearer.
function showCount(...values) {
console.log(values.length);
}
showCount("a", "b", "c"); // 3
Arrow functions do not have their own arguments object.
Because functions are values, you can pass a function to another function. A function passed for later execution is commonly called a callback.
function processName(name, callback) {
return callback(name);
}
function toUpper(name) {
return name.toUpperCase();
}
console.log(processName("plus2net", toUpper)); // PLUS2NET
Callbacks are widely used with array methods, events, timers, and asynchronous APIs.
A recursive function calls itself. It must have a base case that eventually stops the recursion.
function factorial(n) {
if (n <= 1) {
return 1;
}
return n * factorial(n - 1);
}
console.log(factorial(5)); // 120
Without a reachable base case, recursive calls continue until the runtime's call-stack limit is exceeded.
When a function is stored as an object property and called through the object, it is commonly called a method.
const user = {
name: "Maya",
greet() {
return `Hello, ${this.name}`;
}
};
console.log(user.greet());
A normal method receives this according to how it is called. This is one reason an arrow function is not always suitable as an object method.
JavaScript also has specialized function forms. An async function always returns a Promise and enables await inside its body. A generator function uses function* and can pause and resume with yield. These are advanced forms; the normal declaration, expression, and arrow-function patterns above are the foundation.
async function getValue() {
return 42;
}
function* numbers() {
yield 1;
yield 2;
}
return: a calculated value is not sent back automatically from a normal block-bodied function.const function expression too early: function declarations are hoisted differently from expressions.this, arguments, or constructor behavior.Related tutorials: adding JavaScript to an HTML page, JavaScript variables, for loops, and error handling with try...catch.
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.