Functions in JavaScript

A function in JavaScript is a block of reusable code that performs a specific task. Functions are used to avoid repetition and to structure code in a more organized way. Functions can be called whenever needed, and they can accept parameters and return a value.

Types of Functions in JavaScript:

Syntax of Functions:

Function Declaration Syntax


function myFunction() {
    console.log("Hello, World!");
}

Example of Function Declaration in JavaScript:

This example demonstrates a simple function declaration that prints "Hello, World!" when called.

Example


function myFunction() {
    console.log("Hello, World!");
}
myFunction();

Output

Hello, World!

Function Expression Syntax:

Function Expression Syntax


const myFunction = function() {
    console.log("Function Expression Example");
};

Example of Function Expression in JavaScript:

This example demonstrates a function expression where the function is assigned to a variable and called.

Example


const myFunction = function() {
    console.log("Function Expression Example");
};
myFunction();

Output

Function Expression Example

Arrow Function Syntax:

Arrow Function Syntax


const myFunction = () => {
    console.log("Arrow Function Example");
};

Example of Arrow Function in JavaScript:

This example demonstrates an arrow function that prints a message.

Example


const myFunction = () => {
    console.log("Arrow Function Example");
};
myFunction();

Output

Arrow Function Example

Key Points on Functions: