JavaScript Functions

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 and Calling a JavaScript Function Top ↑

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.

Function Parameters and Arguments Top ↑

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.

Returning a Value from a Function Top ↑

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.

What Does a Function Return Without return? Top ↑

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.

Default Parameter Values Top ↑

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

Accepting Many Arguments with Rest Parameters Top ↑

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

Function Expressions Top ↑

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 Top ↑

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.

Local, Global and Block Scope in Functions Top ↑

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.

Nested Functions and Closures Top ↑

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 Declaration Hoisting Top ↑

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.

Passing Objects and Arrays to Functions Top ↑

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.

The arguments Object vs Rest Parameters Top ↑

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.

Functions as Values and Callback Functions Top ↑

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.

Recursive Functions Top ↑

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.

Functions Used as Object Methods Top ↑

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.

Other Function Forms: async and Generator Functions Top ↑

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;
}

Common JavaScript Function Mistakes Top ↑

  • Defining but never calling: a declaration alone does not execute the function.
  • Forgetting return: a calculated value is not sent back automatically from a normal block-bodied function.
  • Confusing parameters and arguments: parameters belong to the definition; arguments belong to the call.
  • Relying on implicit type conversion: validate or convert user input when numeric or other specific types are required.
  • Overusing global variables: local variables and parameters make functions easier to reason about and reuse.
  • Calling a const function expression too early: function declarations are hoisted differently from expressions.
  • Using an arrow function when you need its own this, arguments, or constructor behavior.
  • Mutating objects unintentionally: changes to object properties can be visible outside the function.
  • Recursion without a base case: this can exhaust the call stack.

Related tutorials: adding JavaScript to an HTML page, JavaScript variables, for loops, and error handling with try...catch.

JavaScript Basics




Subscribe to our YouTube Channel here



plus2net.com










✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer