Techoceanhub logo

Function Declarations and Expressions

In programming, particularly in languages like JavaScript, functions are fundamental constructs used to encapsulate a block of code that can be called and executed at any point in a program. There are two primary ways to define functions: function declarations and function expressions. Let me explain each with an example:

Function Declaration

A function declaration is a statement that defines a named function. It’s typically hoisted to the top of its scope, which means you can call the function before it appears in the code.

function functionName(parameters) {
    // function body
    // code to be executed
    return value; // optional
}

Example

// Function declaration
function greet(name) {
    return `Hello, ${name}!`;
}

// Calling the function
console.log(greet('John')); // Output: Hello, John!

In this example:

  • greet is the function name.
  • name is a parameter that the function expects.
  • The function returns a greeting message using the return statement.

Function Expression

A function expression defines a function as part of an expression, typically by assigning it to a variable. Unlike function declarations, function expressions are not hoisted, meaning they cannot be called before they are defined in the code.

const functionName = function(parameters) {
    // function body
    // code to be executed
    return value; // optional
};

Example:

// Function expression
const greet = function(name) {
    return `Hello, ${name}!`;
};

// Calling the function
console.log(greet('Emily')); // Output: Hello, Emily!

In this example:

  • greet is a variable storing an anonymous function.
  • name is a parameter passed to the function.
  • The function returns a greeting message.

Key Differences:

  • Hoisting: Function declarations are hoisted, while function expressions are not.
  • Usage: Function declarations can be called before they are defined in the code (due to hoisting), but function expressions must be defined before they are called.

Both function declarations and function expressions are powerful tools in programming, each with its own use cases and implications for scope and hoisting.

Share:

Categories

Archives

Related Posts

Array Destructuring

Array Destructuring Array destructuring is a powerful syntax introduced in ES6 that allows you to unpack elements from an array

Read More »

Explore our Affiliated partner links

hostgator website plan

Hostgator

Best Website hosting plans & Best for 24/7 support.

hostinger webhosting plan

Hostinger

Reasonable website hosting packages for small business & 24/7 Email support

Elementor pro

Design Worpdress website quickly using Elementor Builder and AI

buy elementor website templates

Buy Elementor Website Template

Buy ready made Elementor Website Template from us & Get Free Elementor pro licence for 1 year .