Online Compiler logoOnline Compiler

JavaScript Tutorial

JavaScript Function Declaration

Function declarations define named functions with the function keyword.

They are hoisted, which means you can call them before they are defined.

Why We Need It

Hoisted functions are convenient for organizing code and separating logic from usage.

They also produce clearer stack traces because the function has a name.

Syntax

function name(params) { ... }

Basic Example

1. Basic declaration

function greet(name) {
  return "Hello " + name;
}

console.log(greet("Riya"));

Declare a function with a name and call it later.

Real World Example

2. Hoisting example

console.log(add(2, 3));

function add(a, b) {
  return a + b;
}

Function declarations can be used before they appear in code.

Multiple Use Cases

Named Functions

Function declarations define a named function using the function keyword.

They are hoisted, so you can call them before the declaration.

Hoisting

Function declarations are hoisted with their bodies.

This means the function is available anywhere in its scope.

Best Uses

Use declarations for core, reusable logic and public APIs.

They are easier to debug because they have stable names.

More Examples

3. Reuse logic

function formatPrice(amount) {
  return "$" + amount.toFixed(2);
}

console.log(formatPrice(99));

Use declarations for reusable formatting logic.

4. Return early

function isAdult(age) {
  if (age < 18) return false;
  return true;
}

console.log(isAdult(20));

Return early to keep logic simple.

Comparison

Without

const add = function(a, b) {
  return a + b;
};

With

function add(a, b) {
  return a + b;
}

Common Mistakes and Fixes

Assuming all functions are hoisted

Only function declarations are hoisted, not expressions.

Using too many globals

Pass data as parameters instead of relying on globals.

Long functions

Keep functions small and focused.

Interview Questions

What is hoisting?

JavaScript moves declarations to the top of their scope before execution.

Are function declarations hoisted?

Yes, both the name and body are hoisted.

Why use function declarations?

They provide named, reusable functions that can be called anywhere in scope.

Practice Problem

Practice: Write a function declaration that calculates the area of a rectangle.

// TODO: function area(width, height)

One Possible Solution

function area(width, height) {
  return width * height;
}

console.log(area(5, 3));

Frequently Asked Questions

Are function declarations hoisted?

Yes, the entire declaration is hoisted.

Can I redeclare a function?

Yes, later declarations overwrite earlier ones in the same scope.

When should I use declarations?

For reusable or core functions that you want available throughout a scope.

Try It Yourself

Try calling the function before and after the declaration.