javascript

Function


 

A function is a block of code designed to perform a specific task. Functions are used to organize code, make it more modular, and facilitate code reuse.


Syntax: 

function function_name(parameter1, parameter2,...) {
    // Your code
    return value;
}

// Calling the function
function_name(arguments...);

 

Example:

// Define a function named "hello"
function hello(name) {
    console.log("Welcome, " + name + "!");
}

// Call the function
hello("Coders"); // Output: Welcome, Coders!

 

Explanation:

  • function hello(name) is the function declaration. It defines a function named "hello" that takes one parameter, "name".
  • console.log("Welcome, " + name + "!"); is the code block inside the function that prints a message to the console.
  • hello("Coders"); is the function call. It executes the "hello" function with the argument "Coders", causing it to print "Welcome, Coders!" to the console.

 

Function Expression:

It is another way to define a function.

 

Example:

let hello = function(name) {
    console.log("Welcome, " + name + "!");
}

let str = hello("Coders");
console.log(str); // Output: Welcome, Coders!

 

Note:

A JavaScript function is executed when it is invoked.