JavaScript function declaration


A function declaration in JavaScript is a way to define a function with a specific name and a block of code to be executed when the function is called. Function declarations are hoisted, meaning they are available throughout the scope in which they are defined, even if you call them before they appear in the code. Here’s a detailed look at function declarations:

Syntax

The basic syntax of a function declaration is:

function functionName(parameters) { // Code to be executed }

Components

  1. function Keyword: This keyword is used to define a function.
  2. functionName: The name you give to the function. Function names should be descriptive of what the function does.
  3. parameters: Optional. A list of parameters that the function can accept. These are placeholders for the values that will be passed to the function when it is called.
  4. Function Body: The block of code enclosed in {} that defines what the function does. This code runs when the function is called.

Examples

  1. Basic Function Declaration

    function greet(name) { return `Hello, ${name}!`; } console.log(greet('Alice')); // 'Hello, Alice!'
    • Here, greet is a function that takes one parameter name and returns a greeting message.
  2. Function with Multiple Parameters

    function add(a, b) { return a + b; } console.log(add(5, 3)); // 8
    • This function add takes two parameters a and b and returns their sum.
  3. Function without Parameters

    function sayHello() { console.log('Hello, World!'); } sayHello(); // 'Hello, World!'
    • The sayHello function does not take any parameters and simply logs a message to the console.

Hoisting

Function declarations are hoisted to the top of their containing scope. This means you can call the function before it is defined in the code.

console.log(square(5)); // 25 function square(x) { return x * x; }

In the example above, square can be called before its declaration because the function declaration is hoisted.

Scope

A function declared in a block scope (like within an if statement or a loop) is only available within that block.

if (true) { function blockScopedFunction() { console.log('I am inside a block.'); } } blockScopedFunction(); // 'I am inside a block.'

Key Points

  • Hoisting: Function declarations are hoisted, so you can use them before their actual declaration in the code.
  • Name: Functions defined with a declaration must have a name.
  • Scope: Functions declared in block scopes are accessible within those blocks.

Function declarations are a fundamental aspect of JavaScript and are used to create reusable pieces of code. They allow for more organized and manageable code, particularly in larger programs.